Overload an array in PHP | Overload a multidimentional array in PHP | On set array call a function in PHP
Published by Nicholas Dunbar on February 9th, 2014
If you wanted to overload an array so that you can put your own logic inside of the get and set actions for an array using the syntax $array['property'] try starting with the class bellow and build off it.
Example:
//create array
$obj = new CustomArray();
//set array
$obj['assoc']['child'] = "gerald";
//print value
echo "\$obj['assoc']['child'] = {$obj['assoc']['child']}\n";
//print array
echo "print array : \n $obj";
//remove element
unset($obj['assoc']['child']);
//check to make sure it is not there
if (!isset($obj['assoc']['child'])){
echo "child removed\n";
}
//print array
echo "print array : \n $obj";
output:
$obj['assoc']['child'] = gerald
print array :
Array
(
[assoc] => Array
(
[child] => gerald
)
)
child removed
print array :
Array
(
[assoc] => Array
(
)
)
Our custom overloaded array seems to function just like the original in the above situation.
Code for CustomArray.php :
class CustomArray extends ArrayObject {
public function __construct($array = NULL)
{
if ($array != NULL){
foreach($array as $key => $value) {
if(is_array($value)){
$value = new CustomArray($value);
}
$this->offsetSet($key, $value);
}
}
}
public function offsetSet($i, $v) {
if (is_array($v)){
$newProp = new CustomArray();
foreach($v as $key=>$value){
$newProp[$key] = $value;
}
parent::offsetSet($i, $newProp);
} else {
parent::offsetSet($i, $v);
}
}
public function offsetGet($i) {
$return = parent::offsetGet($i);
if ($return == NULL){
$newProp = new CustomArray();
parent::offsetSet($i, $newProp);
return $newProp;
}
return $return;
}
public function offsetUnset($i) {
parent::offsetUnset($i);
}
public function offsetExists($i) {
$ret = parent::offsetExists($i);
return $ret;
}
public function __toString()
{
ob_start();
print_r($this->getArrayPrimative());
$output_str = ob_get_contents();
ob_end_clean();
return $output_str;
}
public function getArrayPrimative(){
$output = array();
foreach($this as $key => $value) {
if(gettype($value) == 'object' &&
is_subclass_of($value, 'CustomArray')){
$output[$key] = $value->getArrayPrimative();
} else{
$output[$key] = $this->offsetGet($key);
}
}
return $output;
}
}