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; } 

它是什么原因造成的以及如何解决这个问题?

从任何地方移除& &$this ,这是不需要的。 事实上,我认为你可以在这个代码中删除任何东西 – 根本不需要。

很长的解释

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

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

请注意&符号。 如果我在一个variables上调用modified ,那么它将被修改,如果我调用not_modified ,那么在它返回参数的值之后会是相同的。

PHP的旧版本允许通过这样来模拟not_modified modified行为: not_modified(&$x) 。 这是“通话时间通过参考”。 它被弃用,不应该被使用。

此外,在非常古老的PHP版本(阅读:PHP 4和之前),如果你修改对象,你应该通过引用传递,因此使用&$this 。 这既不必要也不再推荐,因为对象总是在传递给函数时被修改,也就是说,

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

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

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

万一你想知道,通过引用的通话时间传递是一个不推荐的PHPfunction,促进PHP宽松打字。 基本上,它允许你传递一个引用(有点像C指针)给一个没有特别要求的函数。 这是PHP解决scheme中的一个圆孔问题。
在你的情况下, 永远不要引用$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 ?>