PHP 静态方法 init $_SESSION var?
我发现 $_SESSION var 的奇怪功能
class A
{
static function doSomething()
{
$_SESSION['foo'] = 'bar';
}
}
A::doSomething();
var_dump($_SESSION);
正如您可能猜测的那样,会话尚未启动,但 $_SESSION var 已初始化。谁能解释一下到底发生了什么?
I found strange feature with $_SESSION var
class A
{
static function doSomething()
{
$_SESSION['foo'] = 'bar';
}
}
A::doSomething();
var_dump($_SESSION);
As you may guess session is not started but $_SESSION var is initialized. Who can explain what actually happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
$_SESSION 是一个超全局变量,因此无需调用
session_start()
即可访问它。此外,您不需要初始化 $_SESSION 数组
即可像任何其他数组一样使用它
$_SESSION is a superglobal, so it's accessible without the necessity of
session_start()
having been called.Also, you don't need to initialize the $_SESSION array
to use it like any other array
$_SESSION
是一个 超全局数组:因此您始终可以访问该数组。当没有 POST 请求时,这也可以工作,但您可以执行
$_POST['foo'] = 'bar'
。当您尝试转到示例中的另一个页面时,您不会调用 A::doSomething,您会看到
echo $_SESSION['foo'];
会抛出错误,因为您没有调用session_start();
。The
$_SESSION
is a superglobal array:So you can always access this array. This would also work when there was no POST Request, but you could do
$_POST['foo'] = 'bar'
.When you try to go to another page in your example, where you don't call A::doSomething, you will see, that
echo $_SESSION['foo'];
will throw an error, since you didn't callsession_start();
.