【问题标题】:php static in if statementif语句中的php静态
【发布时间】:2011-09-13 16:06:37
【问题描述】:

我的配置文件中有这样的结构:

<?php
if (true) {
    $nonstatic = 1;
    static $config = 1;
}
else {
    $nonstatic = 2;
    static $config = 2;
}

echo $nonstatic;
echo $config;
?>

那么,如果这部分语句为假而 $nonstatic 包含 1,为什么 $config 包含 2?是bug吗?

【问题讨论】:

  • 这是整个脚本,还是有更多代码?
  • if 之外声明变量并简单地在里面分配一个值不是更好吗?我从来没有见过这样使用static 关键字,虽然这并不意味着它是错误的......
  • 似乎最后一个静态声明(不管任何东西)决定了价值。
  • @Michael,当然还有更多代码。这是一个简化版本,描述了我想要达到的目标。
  • @DaveRandom 因为它是一个项目的配置文件,我希望变量是只读的。

标签: php static if-statement variable-declaration


【解决方案1】:

我想这个块被包含在一个函数中。

静态变量的初始化在编译时解决,if the interpreter finds multiple initialisations, it simply takes the bottom one

【讨论】:

  • 特别是,这意味着条件围绕静态初始化无效。
猜你喜欢
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多