PHP 警告:调用时间通过引用已被弃用

php
2022-08-30 08:45:34

我收到警告:对于以下代码行: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;
}

它会导致什么以及如何解决它?


答案 1

从任何地方移除,都不需要。实际上,我认为您可以在此代码中的任何位置删除 - 根本不需要它。&&$this&

长篇解释

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

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

记下该符号。如果我调用一个变量,它将被修改,如果我调用,在它返回后参数的值将是相同的。&modifiednot_modified

允许通过执行以下操作来模拟 与 的旧版本的行为:.这是“通过引用传递调用时间”。它已被弃用,永远不应该使用。modifiednot_modifiednot_modified(&$x)

此外,在非常古老的PHP版本(阅读:PHP 4及更早版本)中,如果修改对象,则应通过引用传递它,因此使用.这既不是必要的,也不推荐,因为对象在传递给函数时总是被修改,即这有效:&$this

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

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

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


答案 2

以防万一你想知道,通过引用传递调用时间是一个已弃用的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
?>

推荐