PHP数组与不存在的索引默认值 [英] PHP array with default value for nonexisting indices

查看:872
本文介绍了PHP数组与不存在的索引默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我爱红宝石的哈希实现,你可以用默认值初始化Hash对象。目前,我与实施PHP类似物体挣扎。目前这是我第一次(非工作)拍摄。

 类DefaultArray扩展ArrayObject的{  保护$ _defaultValue;  公共职能setDefault($设置defaultValue){
    $这个 - > _defaultValue = $设置defaultValue;
  }  公共职能offsetExists($指数){
    返回true;
  }  公共职能offsetGet($指数){
    如果(!父:: offsetExists($指数)){
      如果(is_object($这个 - > _defaultValue))
        $默认= $克隆 - 这 - GT; _defaultValue;
      其他
        $默认= $这个 - > _defaultValue;      父:: offsetSet($指数,$默认);
    }
    返回父:: offsetGet($指数);
  }
}$ DA =新DefaultArray();
断言($ DA [虚拟] == NULL);
$ DA-> setDefault = 1;
断言($ DA [dummy2] == 1);

第二断言将失败。通过code步进显示offsetGet被调用,执行if子句。然而任何数组值为null。任何想法替代实现?

我已经厌倦了写

 如果(!使用isset($ myArr,该['值']))
    $ myArr,该['值'] =新MyObj中();
$ myArr,该['值'] - > =设为myVal 5;

而不是只是写

  $ myArr,该['值']  - > =设为myVal 5;


解决方案

  $ DA-> setDefault(1);

您还可以使用__construct神奇的功能:

 类DefaultArray扩展ArrayObject的
{
    公共职能__construct($值= NULL){
        如果(is_null($值))
        {
            $这个 - >值=默认;
        }其他{
            $这个 - >价值= $价值;
        }
    }
}

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;
        }
    }
}

这篇关于PHP数组与不存在的索引默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆