简体   繁体   English

ZF2 - 你如何访问会话容器中的会话变量?

[英]ZF2 - How are you supposed to access session vars in a session container?

I create a container like so: 我创建一个像这样的容器:

$frontend = new SessionContainer('frontend', null);

I set a variable like so: 我设置了一个变量:

$frontend->offsetSet('foo',$bar);

My question is, when you need to access this somewhere else, are you really supposed to instantiate a new SessionContainer with the same key everywhere you go and grab the var? 我的问题是,当你需要在其他地方访问它时,你真的应该在任何地方使用相同的密钥实例化一个新的SessionContainer并获取var吗? Or, is the session data being passed around in another variable available in the controller or something? 或者,会话数据是否在控制器中可用的另一个变量中传递?

The preferred practice is to directly access the session values as if they were properties of the instantiated container object. 首选实践是直接访问会话值,就好像它们是实例化容器对象的属性一样。

$frontend = new SessionContainer('frontend');
$bar = $frontend->foo;

The session container class does the rest of the work behind the scenes by calling: 会话容器类通过调用以下方式完成幕后的其余工作:

$frontend->__get('foo');

which in turn calls: 反过来调用:

$frontend->offsetGet('foo');

Using the first example above helps improve readability. 使用上面的第一个示例有助于提高可读性。 By the same token you can use: 出于同样的原因,您可以使用:

$frontend->foo = 'bar';

Behind the scenes this calls: 在幕后,这称之为:

$frontend->__set('foo', 'bar');

... and then: ... 接着:

$frontend->offsetSet('foo', 'bar');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM