2

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.

1
  • Check my solution and let me know if not solve. Commented Dec 3, 2018 at 13:09

1 Answer 1

2

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;
    }
}
9
  • please upvote answer :) So, it will useful for other also. Commented Dec 3, 2018 at 13:29
  • Happy coding !! Happy to help :) Commented Dec 3, 2018 at 13:29
  • 1
    Sure, but you never used to upvote my useful questions ;-)
    – Ajwad Syed
    Commented Dec 3, 2018 at 13:35
  • I guess it was just a typo ... //remove "$" from orderId ... public or protected should not matter ;)
    – sv3n
    Commented Dec 3, 2018 at 14:30
  • Btw ... from dev docs: 2.7. All non-public properties and methods SHOULD be private. ... Recommending protected visibilty seems wrong.
    – sv3n
    Commented Dec 3, 2018 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.