__get()获取子项,检测子项是否存在

时间:2013-05-23 15:01:31

标签: php

我有一个PHP实体类,其中每个实体可能包含多个子实体,并且正在使用__get()从父级降级以查找其子级。

$parent->Child1->Child2->Child3->value;

public function __get($name) {
    $name = preg_replace('/![A-z ]+/', '', $name);
        // $child = getByName($name, $parentid)
    if ($child = $this->getByName(str_replace('_', ' ', $name), $this->id)) {
    return $child;
    } else {
        return false;
    }
}

但是,如果任何子实体不存在,它会失败“尝试获取非对象的属性......”除了执行以下操作之外,还有更好的方法可以防止这种情况吗?

if(isset($parent) && is_object($parent->Child1) && is_object($parent->Child1->Child2)

1 个答案:

答案 0 :(得分:1)

我可以想到两个解决方法:


嵌套if s:

    if($child = $parent->Child) {
      if($child2 = $child->Child2) {
        if($child3 = $child2->Child3) {
          // use $child3->Value
        }
      }
    }

辅助功能(当然,这种方法失去了智能感知):

    function getDescendant($parent) {
      $args = func_get_args();
      $names = array_slice($args, 1);
      $result = $parent;
      while(count($names)) {
        $name = array_shift($names);
        if(isset($result->$name)) {
          $result = $result->$name;
        } else {
          return NULL;
        }
      }
      return $result;
    }

    if($c3 = getDescendant($parent, 'Child1', 'Child2', 'Child3')) {
      // use $c3->value;
    }