-1
$a = true;

1,new test($a);

2,new test(true);

它们(1,2)之间有区别吗,如果有,那是什么?谢谢你,。

4

3 回答 3

4

那么另一个使用变量,另一个不使用。在这种情况下,这会导致致命错误:

class test {

    public function __construct( &$a )
    {

    }
}

$a = true;

new test($a);

new test(true); //Fatal error because this cannot be passed by reference
于 2012-06-26T11:43:51.860 回答
1

严格来说,这取决于测试是如何定义的。

如果test定义为通过引用传递输入参数,2则将引发致命错误,因为true它是文字值。

此外,test可能会产生副作用,这意味着您执行行12事项的顺序。

于 2012-06-26T11:45:30.993 回答
1

这取决于test类的构造函数。在常规的按值传递构造函数中,它们完全相同:

class test {
  public $b;
  function __construct($a) { $this->b = $a; }
}

正如预期的那样,这$obj->b将是true您的两个陈述。

另一方面,如果您通过引用传递,如果稍后更改全局,您可能会得到不同的结果$a。例子:

class test {
  public $b;
  function __construct( &$a ) { $this->b = &$a; }
}

$a = true;
$obj = new test($a);
$a = false;

$obj->bfalse在这种情况下,因为它是对$a! 使用引用,您也可以反过来做,$a从构造函数中更改:

class test {
  function __construct( &$a ) { $a = false; }
}

$a = true;
$obj = new test($a);

$a现在即使在全局范围内也是错误的!

此外,new test(true)通过引用传递时不可能这样做,因为您不能引用文字值,只能引用其他变量。

于 2012-06-26T11:47:43.960 回答