M2 | How to create global variable that can be used only in the same class?Unit Test for overwrite collection class in magento2I created a custom module ,but getting error, not able to figure out what the error is about. How to get out of this error?Magento 2.1: Invoke urlBuilder->getUrl() in a controller in a custom moduleProceeding to an exception page after save new categoryMagento 2: How to override newsletter Subscriber modelMagento 2: Add a product to the cart programmaticallyMagento 2: I Want to add multiple product using checkboxHow can I set a global variable in Magento 2?Magento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 Can't view module's front end page output?
Taxi Services at Didcot
What is wrong with this proof that symmetric matrices commute?
Winning Strategy for the Magician and his Apprentice
How did they achieve the Gunslinger's shining eye effect in Westworld?
How to tell your grandparent to not come to fetch you with their car?
What can plausibly explain many of my very long and low-tech bridges?
Where does "0 packages can be updated." come from?
How water is heavier than petrol eventhough its molecular weight less than petrol?
Should an arbiter claim draw at a K+R vs K+R endgame?
Implement Homestuck's Catenative Doomsday Dice Cascader
Can a user sell my software (MIT license) without modification?
Can anyone identify this tank?
Do simulator games use a realistic trajectory to get into orbit?
What is the actual quality of machine translations?
Why would future John risk sending back a T-800 to save his younger self?
Trapping Rain Water
How to retract an idea already pitched to an employer?
When conversion from Integer to Single may lose precision
Genetic limitations to learn certain instruments
What should the arbiter and what should have I done in this case?
Does an ice chest packed full of frozen food need ice?
What makes Ada the language of choice for the ISS's safety-critical systems?
How to chain Python function calls so the behaviour is as follows
Comparing and find out which feature has highest shape area in QGIS?
M2 | How to create global variable that can be used only in the same class?
Unit Test for overwrite collection class in magento2I created a custom module ,but getting error, not able to figure out what the error is about. How to get out of this error?Magento 2.1: Invoke urlBuilder->getUrl() in a controller in a custom moduleProceeding to an exception page after save new categoryMagento 2: How to override newsletter Subscriber modelMagento 2: Add a product to the cart programmaticallyMagento 2: I Want to add multiple product using checkboxHow can I set a global variable in Magento 2?Magento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 Can't view module's front end page output?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
The scenario is I have multiple if-conditions to create product programmatically or load at controller action. I need a single variable who's value should be updating through different functions.
I have tried custom php ways but are not working. How can I achieve this?
Edit
Here is my class, I want to create product one(first) time and after that each time same product should gets load so that it could be added to cart programmatically. I am loading product using SKU. To read code please focus on $sku variable which I want to make global or static.
class Index extends MagentoFrameworkAppActionAction
protected $resultPageFactory;
protected $session;
protected $sku;
private $productRepository;
public function __construct(
FormKey $formKey,
Cart $cart,
Product $product,
MagentoFrameworkAppActionContext $context,
MagentoCustomerModelSession $customerSession,
MagentoCatalogApiProductRepositoryInterface $productRepository,
PageFactory $resultPageFactory
)
$this->session = $customerSession;
$this->formKey = $formKey;
$this->sku = $sku;
$this->cart = $cart;
$this->productRepository = $productRepository;
$this->product = $product;
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
public function execute()
if (!$this->session->isLoggedIn())
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('customer/account/login');
return $resultRedirect;
else
$resultPage = $this->resultPageFactory->create();
$resultPage->getConfig()->getTitle()->set(__('My Wallet'));
$vat_exempt_name = $this->getRequest()->getPost('vat_exempt_name');
//...........Load Product...............//
$product= $this->loadMyProduct();
$ID = $product->getId();
//.............. For Add to Cart .........//
$productId =$ID;
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $productId,
'qty' =>1
);
$product = $this->product->load($productId);
$this->cart->addProduct($product, $params);
$this->cart->save();
return $resultPage;
public function loadMyProduct()
if (empty($this->sku))
$this->createProduct();
else
return $this->productRepository->get($this->sku);
public function createProduct()
$posted = $this->getRequest()->getParam('vat_exempt_name');
$objectManager = MagentoFrameworkAppObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create('MagentoCatalogModelProduct');
$product->setSku('my-sku44'); // I need this SKU to be set for global variable $sku
$product->setName('Wallet Amount'); // Name of Product
$product->setAttributeSetId(4); // Attribute set id
$product->setStatus(1); // Status on product enabled/ disabled 1/0
$product->setWebsiteIds(array(1));
$product->setWeight(10); // weight of product
$product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
$product->setTaxClassId(0); // Tax class id
$product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
$product->setPrice(199); // price of product
$product->setStockData(
array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 99999
)
);
$product = $product->save();
$ID = $product->getId();
//global $sku;
$this->sku = $product->getSku(); // here global variable $sku should update
Thanks.
magento2 php global-variable
add a comment |
The scenario is I have multiple if-conditions to create product programmatically or load at controller action. I need a single variable who's value should be updating through different functions.
I have tried custom php ways but are not working. How can I achieve this?
Edit
Here is my class, I want to create product one(first) time and after that each time same product should gets load so that it could be added to cart programmatically. I am loading product using SKU. To read code please focus on $sku variable which I want to make global or static.
class Index extends MagentoFrameworkAppActionAction
protected $resultPageFactory;
protected $session;
protected $sku;
private $productRepository;
public function __construct(
FormKey $formKey,
Cart $cart,
Product $product,
MagentoFrameworkAppActionContext $context,
MagentoCustomerModelSession $customerSession,
MagentoCatalogApiProductRepositoryInterface $productRepository,
PageFactory $resultPageFactory
)
$this->session = $customerSession;
$this->formKey = $formKey;
$this->sku = $sku;
$this->cart = $cart;
$this->productRepository = $productRepository;
$this->product = $product;
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
public function execute()
if (!$this->session->isLoggedIn())
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('customer/account/login');
return $resultRedirect;
else
$resultPage = $this->resultPageFactory->create();
$resultPage->getConfig()->getTitle()->set(__('My Wallet'));
$vat_exempt_name = $this->getRequest()->getPost('vat_exempt_name');
//...........Load Product...............//
$product= $this->loadMyProduct();
$ID = $product->getId();
//.............. For Add to Cart .........//
$productId =$ID;
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $productId,
'qty' =>1
);
$product = $this->product->load($productId);
$this->cart->addProduct($product, $params);
$this->cart->save();
return $resultPage;
public function loadMyProduct()
if (empty($this->sku))
$this->createProduct();
else
return $this->productRepository->get($this->sku);
public function createProduct()
$posted = $this->getRequest()->getParam('vat_exempt_name');
$objectManager = MagentoFrameworkAppObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create('MagentoCatalogModelProduct');
$product->setSku('my-sku44'); // I need this SKU to be set for global variable $sku
$product->setName('Wallet Amount'); // Name of Product
$product->setAttributeSetId(4); // Attribute set id
$product->setStatus(1); // Status on product enabled/ disabled 1/0
$product->setWebsiteIds(array(1));
$product->setWeight(10); // weight of product
$product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
$product->setTaxClassId(0); // Tax class id
$product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
$product->setPrice(199); // price of product
$product->setStockData(
array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 99999
)
);
$product = $product->save();
$ID = $product->getId();
//global $sku;
$this->sku = $product->getSku(); // here global variable $sku should update
Thanks.
magento2 php global-variable
add the code you tried much better
– magefms
May 29 at 11:09
@magefms I have updated question.
– Ajwad Taqvi
May 29 at 11:37
add a comment |
The scenario is I have multiple if-conditions to create product programmatically or load at controller action. I need a single variable who's value should be updating through different functions.
I have tried custom php ways but are not working. How can I achieve this?
Edit
Here is my class, I want to create product one(first) time and after that each time same product should gets load so that it could be added to cart programmatically. I am loading product using SKU. To read code please focus on $sku variable which I want to make global or static.
class Index extends MagentoFrameworkAppActionAction
protected $resultPageFactory;
protected $session;
protected $sku;
private $productRepository;
public function __construct(
FormKey $formKey,
Cart $cart,
Product $product,
MagentoFrameworkAppActionContext $context,
MagentoCustomerModelSession $customerSession,
MagentoCatalogApiProductRepositoryInterface $productRepository,
PageFactory $resultPageFactory
)
$this->session = $customerSession;
$this->formKey = $formKey;
$this->sku = $sku;
$this->cart = $cart;
$this->productRepository = $productRepository;
$this->product = $product;
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
public function execute()
if (!$this->session->isLoggedIn())
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('customer/account/login');
return $resultRedirect;
else
$resultPage = $this->resultPageFactory->create();
$resultPage->getConfig()->getTitle()->set(__('My Wallet'));
$vat_exempt_name = $this->getRequest()->getPost('vat_exempt_name');
//...........Load Product...............//
$product= $this->loadMyProduct();
$ID = $product->getId();
//.............. For Add to Cart .........//
$productId =$ID;
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $productId,
'qty' =>1
);
$product = $this->product->load($productId);
$this->cart->addProduct($product, $params);
$this->cart->save();
return $resultPage;
public function loadMyProduct()
if (empty($this->sku))
$this->createProduct();
else
return $this->productRepository->get($this->sku);
public function createProduct()
$posted = $this->getRequest()->getParam('vat_exempt_name');
$objectManager = MagentoFrameworkAppObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create('MagentoCatalogModelProduct');
$product->setSku('my-sku44'); // I need this SKU to be set for global variable $sku
$product->setName('Wallet Amount'); // Name of Product
$product->setAttributeSetId(4); // Attribute set id
$product->setStatus(1); // Status on product enabled/ disabled 1/0
$product->setWebsiteIds(array(1));
$product->setWeight(10); // weight of product
$product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
$product->setTaxClassId(0); // Tax class id
$product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
$product->setPrice(199); // price of product
$product->setStockData(
array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 99999
)
);
$product = $product->save();
$ID = $product->getId();
//global $sku;
$this->sku = $product->getSku(); // here global variable $sku should update
Thanks.
magento2 php global-variable
The scenario is I have multiple if-conditions to create product programmatically or load at controller action. I need a single variable who's value should be updating through different functions.
I have tried custom php ways but are not working. How can I achieve this?
Edit
Here is my class, I want to create product one(first) time and after that each time same product should gets load so that it could be added to cart programmatically. I am loading product using SKU. To read code please focus on $sku variable which I want to make global or static.
class Index extends MagentoFrameworkAppActionAction
protected $resultPageFactory;
protected $session;
protected $sku;
private $productRepository;
public function __construct(
FormKey $formKey,
Cart $cart,
Product $product,
MagentoFrameworkAppActionContext $context,
MagentoCustomerModelSession $customerSession,
MagentoCatalogApiProductRepositoryInterface $productRepository,
PageFactory $resultPageFactory
)
$this->session = $customerSession;
$this->formKey = $formKey;
$this->sku = $sku;
$this->cart = $cart;
$this->productRepository = $productRepository;
$this->product = $product;
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
public function execute()
if (!$this->session->isLoggedIn())
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('customer/account/login');
return $resultRedirect;
else
$resultPage = $this->resultPageFactory->create();
$resultPage->getConfig()->getTitle()->set(__('My Wallet'));
$vat_exempt_name = $this->getRequest()->getPost('vat_exempt_name');
//...........Load Product...............//
$product= $this->loadMyProduct();
$ID = $product->getId();
//.............. For Add to Cart .........//
$productId =$ID;
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $productId,
'qty' =>1
);
$product = $this->product->load($productId);
$this->cart->addProduct($product, $params);
$this->cart->save();
return $resultPage;
public function loadMyProduct()
if (empty($this->sku))
$this->createProduct();
else
return $this->productRepository->get($this->sku);
public function createProduct()
$posted = $this->getRequest()->getParam('vat_exempt_name');
$objectManager = MagentoFrameworkAppObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create('MagentoCatalogModelProduct');
$product->setSku('my-sku44'); // I need this SKU to be set for global variable $sku
$product->setName('Wallet Amount'); // Name of Product
$product->setAttributeSetId(4); // Attribute set id
$product->setStatus(1); // Status on product enabled/ disabled 1/0
$product->setWebsiteIds(array(1));
$product->setWeight(10); // weight of product
$product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
$product->setTaxClassId(0); // Tax class id
$product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
$product->setPrice(199); // price of product
$product->setStockData(
array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 99999
)
);
$product = $product->save();
$ID = $product->getId();
//global $sku;
$this->sku = $product->getSku(); // here global variable $sku should update
Thanks.
magento2 php global-variable
magento2 php global-variable
edited May 30 at 6:53
Ajwad Taqvi
asked May 29 at 11:09
Ajwad TaqviAjwad Taqvi
502116
502116
add the code you tried much better
– magefms
May 29 at 11:09
@magefms I have updated question.
– Ajwad Taqvi
May 29 at 11:37
add a comment |
add the code you tried much better
– magefms
May 29 at 11:09
@magefms I have updated question.
– Ajwad Taqvi
May 29 at 11:37
add the code you tried much better
– magefms
May 29 at 11:09
add the code you tried much better
– magefms
May 29 at 11:09
@magefms I have updated question.
– Ajwad Taqvi
May 29 at 11:37
@magefms I have updated question.
– Ajwad Taqvi
May 29 at 11:37
add a comment |
2 Answers
2
active
oldest
votes
I think I'm more going to answer a "php question" than a "magento question" here.
I would have use
$this->sku
and declare it with the others (protected $resultPageFactory;protected $session;private $productRepository;)
Its value will be updated in the object rather than in the method.
I Hope I'm clear enough ;)
If not, there is the documentation.
https://www.php.net/manual/fr/language.oop5.properties.php
New contributor
Hi, I have updated code as you suggested see code in question, this is how updated..but it is throwing exception: Exception #0 (Exception): Notice: Undefined variable: sku
– Ajwad Taqvi
May 30 at 6:58
You might need to declare it in your construcor or the first time you call it. Show me your new version of the code ?
– Mric
May 30 at 12:26
how can we declare it in constructor ?
– Ajwad Taqvi
May 30 at 12:41
$this->sku = ''; (in the constructor). I'm not sure it's the best way, but at least it works
– Mric
May 30 at 14:08
add a comment |
I solved problem using core session to store value and access globally, here is example to understand concept:
use MagentoFrameworkSessionSessionManagerInterface 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');
Get your variable value anywhere by core session as:
public function getValue()
$this->_coreSession->start();
return $this->_coreSession->getMyVariable();
We can also unset session variable by
public function unsetValue()
$this->_coreSession->start();
return $this->_coreSession->unsMyVariable();
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f276570%2fm2-how-to-create-global-variable-that-can-be-used-only-in-the-same-class%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
I think I'm more going to answer a "php question" than a "magento question" here.
I would have use
$this->sku
and declare it with the others (protected $resultPageFactory;protected $session;private $productRepository;)
Its value will be updated in the object rather than in the method.
I Hope I'm clear enough ;)
If not, there is the documentation.
https://www.php.net/manual/fr/language.oop5.properties.php
New contributor
Hi, I have updated code as you suggested see code in question, this is how updated..but it is throwing exception: Exception #0 (Exception): Notice: Undefined variable: sku
– Ajwad Taqvi
May 30 at 6:58
You might need to declare it in your construcor or the first time you call it. Show me your new version of the code ?
– Mric
May 30 at 12:26
how can we declare it in constructor ?
– Ajwad Taqvi
May 30 at 12:41
$this->sku = ''; (in the constructor). I'm not sure it's the best way, but at least it works
– Mric
May 30 at 14:08
add a comment |
I think I'm more going to answer a "php question" than a "magento question" here.
I would have use
$this->sku
and declare it with the others (protected $resultPageFactory;protected $session;private $productRepository;)
Its value will be updated in the object rather than in the method.
I Hope I'm clear enough ;)
If not, there is the documentation.
https://www.php.net/manual/fr/language.oop5.properties.php
New contributor
Hi, I have updated code as you suggested see code in question, this is how updated..but it is throwing exception: Exception #0 (Exception): Notice: Undefined variable: sku
– Ajwad Taqvi
May 30 at 6:58
You might need to declare it in your construcor or the first time you call it. Show me your new version of the code ?
– Mric
May 30 at 12:26
how can we declare it in constructor ?
– Ajwad Taqvi
May 30 at 12:41
$this->sku = ''; (in the constructor). I'm not sure it's the best way, but at least it works
– Mric
May 30 at 14:08
add a comment |
I think I'm more going to answer a "php question" than a "magento question" here.
I would have use
$this->sku
and declare it with the others (protected $resultPageFactory;protected $session;private $productRepository;)
Its value will be updated in the object rather than in the method.
I Hope I'm clear enough ;)
If not, there is the documentation.
https://www.php.net/manual/fr/language.oop5.properties.php
New contributor
I think I'm more going to answer a "php question" than a "magento question" here.
I would have use
$this->sku
and declare it with the others (protected $resultPageFactory;protected $session;private $productRepository;)
Its value will be updated in the object rather than in the method.
I Hope I'm clear enough ;)
If not, there is the documentation.
https://www.php.net/manual/fr/language.oop5.properties.php
New contributor
New contributor
answered May 29 at 15:01
MricMric
164
164
New contributor
New contributor
Hi, I have updated code as you suggested see code in question, this is how updated..but it is throwing exception: Exception #0 (Exception): Notice: Undefined variable: sku
– Ajwad Taqvi
May 30 at 6:58
You might need to declare it in your construcor or the first time you call it. Show me your new version of the code ?
– Mric
May 30 at 12:26
how can we declare it in constructor ?
– Ajwad Taqvi
May 30 at 12:41
$this->sku = ''; (in the constructor). I'm not sure it's the best way, but at least it works
– Mric
May 30 at 14:08
add a comment |
Hi, I have updated code as you suggested see code in question, this is how updated..but it is throwing exception: Exception #0 (Exception): Notice: Undefined variable: sku
– Ajwad Taqvi
May 30 at 6:58
You might need to declare it in your construcor or the first time you call it. Show me your new version of the code ?
– Mric
May 30 at 12:26
how can we declare it in constructor ?
– Ajwad Taqvi
May 30 at 12:41
$this->sku = ''; (in the constructor). I'm not sure it's the best way, but at least it works
– Mric
May 30 at 14:08
Hi, I have updated code as you suggested see code in question, this is how updated..but it is throwing exception: Exception #0 (Exception): Notice: Undefined variable: sku
– Ajwad Taqvi
May 30 at 6:58
Hi, I have updated code as you suggested see code in question, this is how updated..but it is throwing exception: Exception #0 (Exception): Notice: Undefined variable: sku
– Ajwad Taqvi
May 30 at 6:58
You might need to declare it in your construcor or the first time you call it. Show me your new version of the code ?
– Mric
May 30 at 12:26
You might need to declare it in your construcor or the first time you call it. Show me your new version of the code ?
– Mric
May 30 at 12:26
how can we declare it in constructor ?
– Ajwad Taqvi
May 30 at 12:41
how can we declare it in constructor ?
– Ajwad Taqvi
May 30 at 12:41
$this->sku = ''; (in the constructor). I'm not sure it's the best way, but at least it works
– Mric
May 30 at 14:08
$this->sku = ''; (in the constructor). I'm not sure it's the best way, but at least it works
– Mric
May 30 at 14:08
add a comment |
I solved problem using core session to store value and access globally, here is example to understand concept:
use MagentoFrameworkSessionSessionManagerInterface 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');
Get your variable value anywhere by core session as:
public function getValue()
$this->_coreSession->start();
return $this->_coreSession->getMyVariable();
We can also unset session variable by
public function unsetValue()
$this->_coreSession->start();
return $this->_coreSession->unsMyVariable();
add a comment |
I solved problem using core session to store value and access globally, here is example to understand concept:
use MagentoFrameworkSessionSessionManagerInterface 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');
Get your variable value anywhere by core session as:
public function getValue()
$this->_coreSession->start();
return $this->_coreSession->getMyVariable();
We can also unset session variable by
public function unsetValue()
$this->_coreSession->start();
return $this->_coreSession->unsMyVariable();
add a comment |
I solved problem using core session to store value and access globally, here is example to understand concept:
use MagentoFrameworkSessionSessionManagerInterface 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');
Get your variable value anywhere by core session as:
public function getValue()
$this->_coreSession->start();
return $this->_coreSession->getMyVariable();
We can also unset session variable by
public function unsetValue()
$this->_coreSession->start();
return $this->_coreSession->unsMyVariable();
I solved problem using core session to store value and access globally, here is example to understand concept:
use MagentoFrameworkSessionSessionManagerInterface 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');
Get your variable value anywhere by core session as:
public function getValue()
$this->_coreSession->start();
return $this->_coreSession->getMyVariable();
We can also unset session variable by
public function unsetValue()
$this->_coreSession->start();
return $this->_coreSession->unsMyVariable();
answered May 30 at 11:59
Ajwad TaqviAjwad Taqvi
502116
502116
add a comment |
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f276570%2fm2-how-to-create-global-variable-that-can-be-used-only-in-the-same-class%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
add the code you tried much better
– magefms
May 29 at 11:09
@magefms I have updated question.
– Ajwad Taqvi
May 29 at 11:37