我收到警告: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;
}
Run Code Online (Sandbox Code Playgroud)
它是什么原因以及如何解决它?
Sta*_*asM 144
&从&$this任何地方删除,它是不需要的.事实上,我认为您可以&在此代码中随处删除- 根本不需要它.
很长的解释
PHP允许以两种方式传递变量:"按值"和"按引用".第一种方式("按价值"),你不能修改它们,其他第二种方式("通过参考")你可以:
function not_modified($x) { $x = $x+1; }
function modified(&$x) { $x = $x+1; }
Run Code Online (Sandbox Code Playgroud)
注意&标志.如果我调用modified一个变量,它将被修改,如果我调用not_modified它,它返回后该参数的值将是相同的.
旧版本的PHP允许通过这样做来模拟modifiedwith not_modified的行为:not_modified(&$x).这是"通过引用传递呼叫时间".它已弃用,绝不应使用.
另外,在非常古老的PHP版本中(读取:PHP 4及之前版本),如果修改对象,则应通过引用传递它,从而使用&$this.这既不是必需也不是推荐,因为对象在传递给函数时总是被修改,即这有效:
function obj_modified($obj) { $obj->x = $obj->x+1; }
Run Code Online (Sandbox Code Playgroud)
这会修改,$obj->x即使它正式传递"按值",但传递的是对象句柄(如Java等),而不是对象的副本,就像在PHP 4中一样.
这意味着,除非你做了一些奇怪的事情,否则你几乎不需要传递对象(因此$this通过引用,无论是通话时间还是其他方式).特别是,您的代码不需要它.
Bai*_*ker 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
?>
Run Code Online (Sandbox Code Playgroud)