To get the current customer in Magento 2, you can use the Magento\Customer\Model\Session class, which holds the current customer's session data. Here's how you can do it:

1. Using Customer Session in a Block:

<?php

namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;
use Magento\Customer\Model\Session as CustomerSession;

class CustomBlock extends Template
{
    protected $customerSession;

    public function __construct(
        Template\Context $context,
        CustomerSession $customerSession,
        array $data = []
    ) {
        $this->customerSession = $customerSession;
        parent::__construct($context, $data);
    }

    public function getCurrentCustomer()
    {
        return $this->customerSession->getCustomer();
    }
}

2. Using Customer Session in a Controller:

<?php

namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session as CustomerSession;

class Index extends Action
{
    protected $customerSession;

    public function __construct(
        Context $context,
        CustomerSession $customerSession
    ) {
        $this->customerSession = $customerSession;
        parent::__construct($context);
    }

    public function execute()
    {
        $customer = $this->customerSession->getCustomer();

        // Now you can use $customer for your logic
    }
}

3. Using Customer Session in a Helper:

<?php

namespace Vendor\Module\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Customer\Model\Session as CustomerSession;

class Data extends AbstractHelper
{
    protected $customerSession;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        CustomerSession $customerSession
    ) {
        $this->customerSession = $customerSession;
        parent::__construct($context);
    }

    public function getCurrentCustomer()
    {
        return $this->customerSession->getCustomer();
    }
}

Notes:

  • The getCustomer() method will return an instance of Magento\Customer\Model\Data\Customer which contains customer data like first name, last name, email, etc.
  • Make sure that the customer session is initialised. If you try to get the current customer in an area where the session is not initialised (like in some backend or API contexts), this approach may not work.
This method allows you to retrieve the current customer's information based on the session in Magento 2.