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


__get() fetching children, detect if child exists

我有一个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)

我可以想到两个变通办法:


嵌套if s:

<>之前if($child = $parent-> child) {if($child2 = $child-> child2) {if($child3 = $child2-> $child3) {//使用$child3->Value}}}之前

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

<>之前getDescendant($parent) {$args = func_get_args();$names = array_slice($args, 1);$result = $parent;而(count($名称)){$name = array_shift($names);如果收取(结果->名称)美元){$result = $result->$name;} else {返回NULL;}}返回结果美元;}if($c3 = getDescendant($parent, 'Child1', 'Child2', 'Child3')) {//使用$c3->value;}