覆盖超级全局 $_SESSION 是否安全?
用专门的会话对象覆盖超级全局 $_SESSION
是否安全?
class SessionObject implements ArrayAccess { ... }
...
// Session data has just been deserialised from store.
$_SESSION = new SessionObject( $session_data );
...
// Using session object...
$_SESSION['key'] = 27;
$x = $_SESSION->get_data('key2', 'default-value');
Is it safe to overwrite the super-global $_SESSION
with a specialised session object?
class SessionObject implements ArrayAccess { ... }
...
// Session data has just been deserialised from store.
$_SESSION = new SessionObject( $session_data );
...
// Using session object...
$_SESSION['key'] = 27;
$x = $_SESSION->get_data('key2', 'default-value');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
虽然这可能有效,但我认为这不是明智的行为。在我看来,最小惊喜原则不仅适用于用户界面设计,也适用于编程。如果您在脚本中覆盖
$_SESSION
的默认行为,那么将来必须处理您的代码的程序员将会感到非常困惑。我认为以这种方式滥用
$_SESSION
的超全局性质是一种黑客行为,而且是一种令人不快的行为。在我看来,更好的是编写一个具有静态方法的类来获取和设置数据:
然后您可以使用
Session::get('someKey')
或Session 访问它: :get('someKey', 'default')
和Session::set('someKey', 'someValue')
。由于类本质上是全局的,因此您可以从代码中的任何位置访问它。这并不令人惊讶,并且会减少后续的混乱。
如果出于某种设计原因确实想使用对象方法,那么最好实现单例模式。
While this may work, I don't think it's sensible behaviour. The principle of least surprise applies, in my opinion, to programming as much as to user interface design. If you overwrite the default behaviour of
$_SESSION
in your script, that's going to confuse the hell out of some future programmer who has to deal with your code.I think it's a hack -- and an unpleasant one -- to abuse the super-global nature of
$_SESSION
in this way.Better, in my opinion, would be to write a class with static methods to get and set your data:
You could then access this with
Session::get('someKey')
orSession::get('someKey', 'default')
andSession::set('someKey', 'someValue')
.Since classes are inherently global, you could access this from anywhere in your code. It is less surprising, and will result in less confusion down the line.
If you did want to use object methods for some design reason, it might be best to implement the Singleton pattern.
对我来说似乎有点冒险。您检查过 session_set_save_handler 方法吗?它允许您指定要使用的自己的处理程序,而不是尝试覆盖 $_SESSION。
Seems a little risky to me. Have you checked out the session_set_save_handler method? It lets you designate your own handler to use, instead of trying to overwrite $_SESSION.
如果您自己处理会话处理和存储,那么您可以做任何您想做的事。在这方面,$_SESSION 超全局变量可以像任何其他变量一样使用。
只有 PHP 的默认会话处理程序才会对其进行特殊处理。它期望那里有一个普通数组(并且也不能进行数字索引)。如果你想再次使用它,你需要通过关闭调用来撤消花哨的 ArrayObject 包装:
If you deal with session handling and storage yourself, then you can do whatever you please. The $_SESSION superglobal can be used like any other variable in that regard.
It's only PHPs default session handler which treats it specially. It expects a normal array there (and must not be numerically indexed as well). If you wanted to use that again, you would require to undo the fancy ArrayObject wrapping with a shutdown call: