Yes. Exactly.
"$this->a[]" is interpreted as "$this->__get('a')[]".
__get() creates 'temporary variable' for returned value (which is an
array) and then [] refers to 'a new element of this array', but doesn't
change original array. This 'temporary variable' is immediately
destroyed after the expression in which it used.
Thus, "$this->a[] = 1" is equal to:
-----
$tempArray = $this->__get('a');
$tempArray[] = 1;
unset($tempArray);
-----
There is the same problem with strings.
I think good way to manage this is an OO wrappers. It works also for
referencing property outside class scope.
PHP5 sends and returns objects "by reference", thus '[]' will work with
the same object instance, which is stored in an object property.
An example is the Zend_Pdf_PHPArray.
With best regards,
Alexander Veremyev.
Matthew Ratzloff wrote:
I consider this a bug in PHP itself, personally. The solution is
changing __get to something more like this:
// Zend_View_Abstract::__get()
public function __get($key)
{
if ($key[0] != '_') {
if (!isset($this->_vars[$key])) {
$this->_vars[$key] = null;
}
return $this->_vars[$key];
}
}
This is because when you call $this->a[] = 1, PHP actually calls __get
instead of __set. There is no warning, error, or anything. It just
silently fails.
-Matt
----- Original Message ----- From: "Carolina Feher da Silva"
<[EMAIL PROTECTED]>
To: <[email protected]>
Sent: Tuesday, October 31, 2006 7:32 PM
Subject: [fw-general] Strange array bug?
Please paste this code in a view:
$this->a = array();
$this->a[] = 1;
print_r($this->a);
What do you get? I get an *empty* array. How come? I don't understand it.