How to get value in function that is retrieved and stored in a variable of another function in same class | Magento 2

magento.stackexchange https://magento.stackexchange.com/questions/252239

Question

I want to use $orderId value in other functions.

Here is class

<?php
namespace vendor\module\Observer;

use Magento\Framework\Event\ObserverInterface;

class Observer implements ObserverInterface
{
public function __construct(
\Magento\Framework\Registry $registry
) { 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
}

public function execute(\Magento\Framework\Event\Observer $observer) { 
    $order = $observer->getEvent()->getOrder();
    $orderId = $order->getId();
    $customerId = $order->getCustomerId();
}
public function getOrderId(){

$Id = $orderId;
return $Id;
}

}

I tried this:

class Observer implements ObserverInterface
{
public $orderId;
public function __construct(
\Magento\Framework\Registry $registry
) { 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
}

public function execute(\Magento\Framework\Event\Observer $observer) { 
    $order = $observer->getEvent()->getOrder();
    $this->$orderId = $order->getId();
    $customerId = $order->getCustomerId();
}
public function getOrderId(){

$Id = this->$orderId;
return $Id;
}
}

I am Calling getOrderId(); in same class.. but not working

Gone through links like https://stackoverflow.com/questions/519078/making-a-global-variable-accessible-for-every-function-inside-a-class Need a solution in this particular scenario.

Was it helpful?

Solution

Instead of set public, try with set variable private.

class Observer implements ObserverInterface
{
    private $orderId;
    public function __construct(
        \Magento\Framework\Registry $registry
    ) { 
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
    }

    public function execute(\Magento\Framework\Event\Observer $observer) { 
        ...
        $this->orderId = $order->getId(); //remove "$" from orderId
        ...
    }
    public function getOrderId()
    {
        $Id = $this->orderId; //remove "$" from orderId
        return $Id;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top