dongyu5104 2019-03-07 11:29
浏览 61
已采纳

PHP会话变量请求时间

I was wondering wether it makes a difference in speed to save PHP SESSION Variables at the top of a script as Variables or just use the SESSION Variables through the entire script. e.g.

$_SESSION['bar'];

...

<p><?php echo $_SESSION['bar'] ?></p>
<p><?php echo $_SESSION['bar'][0] ?></p>

Or as explained above: Save the SESSION Variable first and then access that variable instead.

$bar = $_SESSION['bar'];

...

<p><?php echo $bar ?></p>
<p><?php echo $bar[0] ?></p>

Does it make any difference? Is PHP Requesting the SESSION Variables every single time from the server again?

  • 写回答

1条回答 默认 最新

  • duanpie2414 2019-03-07 11:37
    关注

    Unless you do these session read/write operations millions of times (e.g. in a loop) you shouldn't be concerned with such micro optimizations. Even if you do them like that, I still think that PHP writes to session whenever that session is closed (not 100% sure about this last one).

    Remember that premature optimization is the root of all evil. :)

    On a more serious note:

    • It's always recommended to move code that's used more than once into a variable or a helper function (DRY principle)
    • By creating a helper function or a "wrapper" class for accessing low level services like Sessions, your code becomes "future proof" and not bound to an implementation. If in the future you decide to replace the storage engine from Session to, e.g, Cookies or Redis, you just change the helper class and the rest of the code keeps working. In other words, try to practice the Orthogonality principle.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!