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.

  • Check my solution and let me know if not solve. – Rohan Hapani Dec 3 '18 at 13:09
1

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;
    }
}
| improve this answer | |
  • please upvote answer :) So, it will useful for other also. – Rohan Hapani Dec 3 '18 at 13:29
  • Happy coding !! Happy to help :) – Rohan Hapani Dec 3 '18 at 13:29
  • 1
    Sure, but you never used to upvote my useful questions ;-) – Ajwad Syed Dec 3 '18 at 13:35
  • +1 from mine :) – Rohan Hapani Dec 3 '18 at 14:20
  • I guess it was just a typo ... //remove "$" from orderId ... public or protected should not matter ;) – sv3n Dec 3 '18 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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