Question

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.

Was it helpful?

Solution

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();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top