PHP 警告: 不推荐通过引用传递调用时间

我收到警告: Call-time pass-by-reference has been deprecated代码如下:

function XML() {
$this->parser = &xml_parser_create();
xml_parser_set_option(&$this->parser, XML_OPTION_CASE_FOLDING, false);
xml_set_object(&$this->parser, &$this);
xml_set_element_handler(&$this->parser, 'open','close');
xml_set_character_data_handler(&$this->parser, 'data');
}
function destruct() {
xml_parser_free(&$this->parser);
}
function & parse(&$data) {
$this->document = array();
$this->stack    = array();
$this->parent   = &$this->document;
return xml_parse(&$this->parser, &$data, true) ? $this->document : NULL;
}

它会导致什么并且如何修复它?

59916 次浏览

&$this删除 &到处,它是不需要的。事实上,我认为你可以删除 &在这段代码的任何地方-它是根本不需要的。

说来话长

PHP 允许以两种方式传递变量: “通过值”和“通过引用”。第一种方法(“通过值”) ,你不能修改它们; 第二种方法(“通过引用”) ,你可以:

     function not_modified($x) { $x = $x+1; }
function modified(&$x) { $x = $x+1; }

注意 &标志。如果我对一个变量调用 modified,它将被修改,如果我调用 not_modified,它返回的参数值将是相同的。

旧版本的 PHP 允许通过这样做来模拟 modifiednot_modified的行为: not_modified(&$x)。这是“通话时间通过引用”。它已经过时了,永远不应该使用。

此外,在非常古老的 PHP 版本中(请阅读: PHP4及以前的版本) ,如果修改对象,应该通过引用传递对象,从而使用 &$this。这既不是必需的,也不是推荐的,因为对象在传递给函数时总是会被修改,也就是说,这可以工作:

   function obj_modified($obj) { $obj->x = $obj->x+1; }

这将修改 $obj->x,即使它的形式是“通过值”传递的,但传递的是对象句柄(如 Java 等) ,而不是对象的副本,如 PHP4。

这意味着,除非您正在执行某些奇怪的操作,否则几乎不需要传递 object (因此 $this通过引用传递,不管是调用时还是其他方式)。特别是,您的代码不需要它。

如果您想知道的话,引用调用时间传递是一个不被推荐的 PHP 特性,它促进了 PHP 松散类型。基本上,它允许您传递一个引用(类似于 C 指针)到一个没有明确要求引用的函数。这是 PHP 对圆孔问题中的方桩的解决方法。
在您的情况下,永远不会参考 $this。在类之外,对它的 $this的引用将不允许您访问它的私有方法和字段。

例如:

<?php
function test1( $test ) {} //This function doesn't want a reference
function test2( &$test ) {} //This function implicitly asks for a reference


$foo = 'bar';
test2( $foo ); //This function is actually given a reference
test1( &$foo ); //But we can't force a reference on test1 anymore, ERROR
?>