. Updated Daily. Editions SDA India   SDA Indonesia
JAX Asia 2008 - Conference for Enterprise Java, SOA, Spring, Web Services, Ajax, Agile and more
BUSINESS ENTERPRISE SOLUTIONS ARCHITECTURE INFORMATION SECURITY WIRELESS & MOBILITY DATA & STORAGE DEVELOPMENT HARDWARE













News

Monday, 22 January 2007

Overview of Overloading Arrays in PHP 5.2.0

 

 

Matthew O’Pinney has a detailed write-up on how to extend ArrayObject to modify overloaded arrays in your class and support PHP 5.2.0. Before he explains how to go about doing this, Matthew provides a brief history about a bug that was reported against Zend_View. The bug report said that the following was now failing in PHP 5.2.0:

$view->foo = array();
$view->foo[] = 42;

A notice was raised stating, Notice: Indirect modification of overloaded property Zend_View:: has no effect."

The bug meant that __get() no longer returned a reference; instead, it returned values in read mode. This made modifying arrays using overloading impossible using traditional methods.

Derick Rethans’ solution to this problem was to use a switch() statement in __get() to cast the returned value explicitly as an array:

public function __get($key)
{
if (is_array($this->_vars[$key])) {
return (array) $this->_vars[$key];
}

return $this->_vars[$key];
}

Since this approach has issues with other array functionalities, such as assigning by reference, Mathew decided the best solution was to have the class extend ArrayObject, such that it allows flexible access to properties in the object:

class My_Class extends ArrayObject
{
public function __construct( = array())
{
// ... some setup

// Allow accessing properties as either array keys or object properties:
parent::__construct(array(), ArrayObject::ARRAY_AS_PROPS);
}
}

Matthew’s solution also put an end to another Zend_View irritiant. With Zend_View it as always difficult to keep public properties—template variables, that is—separate from private/protected properties such as the helper, filter and script paths. But the ArrayObject::ARRAY_AS_PROPS setting prevented such collision from happening and helped simplify the code.

But Matthew ran into some issues with the ArrayObject solution, as there was a bug in PHP 5.2.0, with its interaction with empty() and isset() when used with the ARRAY_AS_PROPS flag. (Note that the bug now stands fixed.)

At this point, Mike Naberezny stepped in and pointed out that as of PHP 5.1, setting undefined public properties no longer raises an E_STRICT notice. So now you can do the following, without encountering any errors:

class Foo
{
public function __set($key, $value)
{
$this->$key = $value;
}
}

$foo = new Foo();
$foo->bar = array();
$foo->bar[] = 42;

 

Read the Post

 
 
print save email comment

print

save

email

comment

 
 

Search SDA Asia

Free eNewsletter

SDA Asia Magazine Free Download
 
 
 
Copyright @ 2008 SDA Asia Magazine - All Right Reserved Privacy Policy | Terms of Use