在这里使用PHP,我决定逐章阅读手册并学习新东西。所以现在我发现了静态变量,这似乎是一个很棒的概念,但我理解的方式是:
每次加载脚本时,静态变量只设置一次。它们可以更改和增加,但实际上不会重新设置。通常在函数中用于设置值,而不是每次函数运行时都必须初始化该变量。
<?php
function count2( $inputNum ) {
static $a = $inputNum;
echo $a++; //Echo and then increment.
}
for ( $i = 0; $i < 10; $i++ ) {
count2(50);
}
?>
我希望这会在50时启动静态$a
var,并增加11次。为什么我会收到错误?
答案 0 :(得分:4)
与任何其他PHP静态变量一样,静态属性只能使用文字或常量初始化;表达式是不允许的。 因此,您可以将静态属性初始化为整数或数组 (例如),您可能不会将其初始化为另一个变量,也就是a 函数返回值,或对象。
我认为你错过了docs(强调我的)那部分:)
答案 1 :(得分:1)
静态变量无法使用另一个变量初始化,其值在运行时才会知道。您必须使用编译时已知的值初始化它。
function count2($inputNum) {
// Initialize only once to an integer (non variable, non-expression)
static $a = 0;
if ($a === 0) {
// If $a is still 0, set it to $inputNum
$a = $inputNum;
}
echo $a++;
}
// First run outputs 25
count2(25);
// 25
// Subsequent runs increment
count2(25);
// 26
count2(25);
// 27
答案 2 :(得分:0)
几乎没有问题:
count2()
10次来反复破坏它。++
运算符,因为您无法更改静态变量constant
也许尝试类似:
<?php
error_reporting(E_ALL);
/* setup */
function set( $input ) {
define( 'A', $input );
}
function tick() {
echo constant( 'A' ) . "\n";
}
/* run */
set( 50 );
for($i=0; $i<10; $i++){
tick();
}
?>
这将输出:
$ php test.php
50
50
50
50
50
50
50
50
50
50