3

I want to know if it's possible to add a global variable all through the site (so that if I need to change it, I would only need to do it once).

It's for an URL.

Dhaduk Mitesh
  • 1,675
  • 1
  • 11
  • 29
Morgan Tartreau
  • 945
  • 3
  • 15
  • 40

1 Answers1

7

You can use core session to store the value to access globally

use Magento\Framework\Session\SessionManagerInterface as CoreSession;

class MyClass
{

    protected $_coreSession;

    public function __construct(
        ...
        CoreSession $coreSession
        ...
    ) {
        $this->_coreSession = $coreSession;
    }

    public function setValue(){
        $this->_coreSession->start();
        $this->_coreSession->setMyVariable('My variable value');
    }
}

Now you can get your variable value anywhere by core seesion

    public function getValue(){
        $this->_coreSession->start();
        return $this->_coreSession->getMyVariable();
    }

You can also unset session variable by

    public function unsetValue(){
        $this->_coreSession->start();
        return $this->_coreSession->unsMyVariable();
    }
Prince Patel
  • 22,708
  • 10
  • 97
  • 119
  • Hi, can you answer please? https://magento.stackexchange.com/questions/290074/magento-2-get-cookie-just-next-after-set-it – Jigar7521 Sep 18 '19 at 12:47