PHP警告:调用时传递引用已被弃用


73

我收到警告: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;
}

它是什么原因以及如何解决?



相关手册页:通过引用传递
Palec,2014年

Answers:


143

&&$this任何地方删除,这是不需要的。实际上,我认为您可以删除&此代码中的所有位置-完全不需要。

详细说明

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

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

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

通过执行以下操作,较旧版本的PHP可以模拟modifiedwithnot_modified的行为:not_modified(&$x)。这是“通过引用传递时间”。不推荐使用,永远不要使用它。

此外,在非常古老的PHP版本中(阅读:PHP 4和更低版本),如果您修改对象,则应通过引用传递它,从而使用&$this。既不需要也不建议这样做,因为在将对象传递给函数时总是会对其进行修改,即可以:

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

$obj->x即使它是按“值”形式正式传递的,也会对此进行修改,但是传递的是对象句柄(如Java等),而不是对象副本,如PHP 4中那样。

这意味着,除非您做一些奇怪的事情,否则几乎不需要传递对象(因此,$this通过引用,无论是调用时间还是其他方式)。特别是,您的代码不需要它。


我也要指出,如果尝试使用调用函数,则显示上述错误,如果使用call_user_func('myfunc', &$param)则不显示call_user_func_array('myfunc', array(&$param))。我不知道为什么,但是,如果有人想阐明一点:)
Matt Fletcher 2013年

1
@MattFletcher因为前者是调用时参考语法,所以已不推荐使用很长时间了。后者只是将参数传递给函数(恰好是call_user_func_array),因此它没有任何问题。因此,是的,您可以使用后一种语法来进行调用时引用的雷达形式,也可以将其用于合法目的-例如为by-ref变量-args函数制作包装器(PDO中的参数化绑定可能是一个例子)。差异是前者始终不是合法的,并且不需要,后者可能是合法的,也可能不是合法的,这取决于用法。
StasM 2013年

2
First way, you can modify them, other way you can't相反:)
Thierry J.

20

万一您想知道,按引用传递呼叫时间是不推荐使用的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
?>

3
“基本上,它使您可以将引用(类似于C指针)传递给没有明确要求的函数。” <-那是好东西。谢谢。
RobW 2012年

需要明确的是,PHP引用根本不像C指针。如果需要类比,它们更像UNIX硬链接。
StasM 2013年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.