tomriddle_1234
tomriddle_1234

Reputation: 3213

How to add a global accessible variable for Phalcon Micro framework?

I'm new to PHP Phalcon and I'm creating a simple REST API backend, I now encounter a problem.

//define $app in index.php
$app = new Micro($di) ;

In one controller I'm trying to define (add) a global accessible variable between controllers at least.

//However, the followings are all not working.
$this->currentWeixinAccessToken = $access_token ;
$this->getDI()->setShared('currentWeixinAccessToken', $access_token);
$this->$currentWeixinAccessToken = $access_token;
$this->di->setShared('currentWeixinAccessToken', $access_token) ;

They can be defined without error, but when I'm using them in another controller,

$access_token = $this->currentWeixinAccessToken;

The error is,

[Sat Jul 30 22:10:20 2016] PHP Notice:  Access to undefined property currentWeixinAccessToken in /home/tom/src/phalcontest/app/controllers/PostsController.php on line 48

And I found some answers here, but they don't work for me. Cross controller variables in Phalcon

Upvotes: 1

Views: 776

Answers (1)

Luke
Luke

Reputation: 2400

When you add something to dependency injector you need to call it through di. That's why you should try using $access_token = $this->di->currentWeixinAccessToken instead in your second controller. Di is by default accessible from controller in full Phalcon, I'm not sure what about micro version. If it doesn't work you can try using \Phalcon\Di::getDefault()->currentWeixinAccessToken or \Phalcon\Di::getDefault()->get('currentWeixinAccessToken')

Upvotes: 1

Related Questions