I am getting the warning: Call-time pass-by-reference has been deprecated
for the following lines of code:
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;
}
What does it cause and how to fix it?
Answer
Remove &
from &$this
everywhere, it is not needed. In fact, I think you can remove &
everywhere in this code - it is not needed at all.
Long explanation
PHP allows to pass variables in two ways: "by value" and "by reference". First way ("by value"), you can't modify them, other second way ("by reference") you can:
function not_modified($x) { $x = $x+1; }
function modified(&$x) { $x = $x+1; }
Note the &
sign. If I call modified
on a variable, it will be modified, if I call not_modified
, after it returns the value of the argument will be the same.
Older version of PHP allowed to simulate behavior of modified
with not_modified
by doing this: not_modified(&$x)
. This is "call-time pass by reference". It is deprecated and should never be used.
Additionally, in very ancient PHP versions (read: PHP 4 and before), if you modify objects, you should pass it by reference, thus the use of &$this
. This is neither necessary nor recommended anymore, as object are always modified when passed to function, i.e. this works:
function obj_modified($obj) { $obj->x = $obj->x+1; }
This would modify $obj->x
even though it formally is passed "by value", but what is passed is object handle (like in Java, etc.) and not the copy of the object, as it was in PHP 4.
This means, unless you're doing something weird, you almost never need to pass object (and thus $this
by reference, be it call-time or otherwise). In particular, your code doesn't need it.
No comments:
Post a Comment