目前使用php5.6版本,刚刚试着了解静态变量,简单写了个方法
class test
{
public function test()
{
static $a = [];
$a[] = 1;
return $a;
}
}
$test = new test();
$a = $test->test();
print_r($a);
输出是
请问这个结果是怎么产生的?我以为结果会是array([0]=>1);
目前使用php5.6版本,刚刚试着了解静态变量,简单写了个方法
class test
{
public function test()
{
static $a = [];
$a[] = 1;
return $a;
}
}
$test = new test();
$a = $test->test();
print_r($a);
输出是
请问这个结果是怎么产生的?我以为结果会是array([0]=>1);
class test{
function test(){
}
}
$test = new test();
$a = $test->test();
相当于
class test{
function __construct(){
}
}
$test = new test();//此时已经 __construct(); 创建时已经调用了
$a = $test->__construct();//第2次调用
4 回答968 阅读
1 回答643 阅读✓ 已解决
2 回答617 阅读
603 阅读
如果我记得没错的话:
$test = new test()的时候已经使得$a[] = 1;你在
$a[] = 1后面var_dump $a就能看到。(此时没有执行$test->test());而你在执行
$test->test()的时候 又执行了$a[] = 1,上面var_dump($a);会输出两个因为是静态变量 所以不会被重新声明,继续往数组里面增加内容。
test()是构造函数,new 的时候会自动执行的。至于为什么是构造函数:引用如下: