2012-06-26 56 views

回答

4

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

class test { 

    public function __construct(&$a) 
    { 

    } 
} 

$a = true; 

new test($a); 

new test(true); //Fatal error because this cannot be passed by reference 
1

严格地说,这取决于如何定义测试。

如果test被限定为使得输入参数是passed by reference,然后2将提高一个致命的错误,因为true是一个文字值。

此外,test可能有副作用,这意味着您执行行12重要的顺序。

1

它取决于test类的构造函数。在常规通按值构造它们是完全一样的:

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

这里,$obj->btrue为您的声明,如预期。

如果,另一方面,你是passing by reference如果你改变了全球$a以后你可能会得到不同的结果。例如:

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

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

$obj->b会在这种情况下false,因为它是$a参考!随着引用,你也可以做它周围的其他方法,从构造方法中改变$a

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

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

$a现在是假的,甚至在全球范围内!

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

+0

哇,为什么这个低估是超越了我...... :( –

+0

SiGanteng,我同意。会很好的解释。 –

相关问题