Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array with default value for nonexisting indices

Tags:

arrays

php

hash

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;
like image 708
chiborg Avatar asked Sep 22 '09 16:09

chiborg


1 Answers

$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;
        }
    }
}
like image 69
erenon Avatar answered Sep 30 '22 19:09

erenon