对于以下代码行,我收到警告: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;
}
它导致了什么以及如何修复它?
发布于 2011-01-12 14:02:16
从任何地方的&$this
中删除&
,它是不需要的。事实上,我认为你可以在这段代码中删除任何地方的&
--根本不需要它。
长文解释
PHP允许以两种方式传递变量:“按值”和“按引用”。第一种方式(“按值”),你不能修改它们,另一种方式(“按引用”),你可以:
function not_modified($x) { $x = $x+1; }
function modified(&$x) { $x = $x+1; }
请注意&
标志。如果我在一个变量上调用modified
,它将被修改,如果我调用not_modified
,在它返回后,参数的值将是相同的。
老版本的PHP允许通过以下方式用not_modified
模拟modified
的行为:not_modified(&$x)
。这是"call-time pass by reference“。它已被弃用,永远不应使用。
此外,在非常古老的PHP版本中(例如:PHP4及更早版本),如果修改对象,则应该通过引用传递它,因此使用了&$this
。这不再是必要的,也不再被推荐,因为对象在传递给函数时总是被修改,也就是说,这是有效的:
function obj_modified($obj) { $obj->x = $obj->x+1; }
这将修改$obj->x
,即使它正式地“按值”传递,但传递的是对象句柄(就像在Java中一样,等等)。而不是对象的副本,就像在PHP4中一样。
这意味着,除非您正在做一些奇怪的事情,否则您几乎不需要传递object (因此通过引用传递$this
,无论是调用时间还是其他方式)。特别是,您的代码不需要它。
发布于 2011-01-12 14:13:15
如果您想知道,调用时通过引用传递是一个被弃用的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
?>
https://stackoverflow.com/questions/4665782
复制相似问题