I love the Hash implementation of Ruby where you can initialize the Hash object with a default value. At the moment I'm struggling with implementing a similar object in PHP. This is my first (non-working) shot at this.
class DefaultArray extends ArrayObject {
protected $_defaultValue;
public function setDefault($defaultValue) {
$this->_defaultValue = $defaultValue;
}
public function offsetExists($index) {
return true;
}
public function offsetGet($index) {
if(!parent::offsetExists($index)) {
if(is_object($this->_defaultValue))
$default = clone $this->_defaultValue;
else
$default = $this->_defaultValue;
parent::offsetSet($index, $default);
}
return parent::offsetGet($index);
}
}
$da = new DefaultArray();
assert($da["dummy"] == null);
$da->setDefault = 1;
assert($da["dummy2"] == 1);
The second assertion will fail. Stepping through the code shows that offsetGet is called and the if clause is executed. Nevertheless any array value is null. Any ideas for alternative implementations?
I'm tired of writing
if(!isset($myarr['value']))
$myarr['value'] = new MyObj();
$myarr['value']->myVal=5;
instead of just writing
$myarr['value']->myVal=5;
$da->setDefault(1);
You can also use the __construct magic function:
class DefaultArray extends ArrayObject
{
public function __construct($value = null){
if(is_null($value))
{
$this->value = 'default';
} else {
$this->value = $value;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With