简体   繁体   中英

Php: Cannot seem to access array property in object

I have a class called Member. I am trying to add a multidimensional array as a property like so:

class Member {

public $name;
public $inheritingMembers;

public function __construct($name, $family) {
    $this->name = $name;
    $this->inheritingMembers = $this->findInheritingMembers($family, $name);
}

function findInheritingMembers($array, $keySearch) {
    foreach ($array as $key => $item){
        if ($key == $keySearch){
            return $item['children'];
        } else {
            if (is_array($item))
                $this->findInheritingMembers($item, $keySearch);
        }
    }
    return false;
}

}

The function "findInherititngMembers" returns a multidimensional array which I can see with var_dump(). The problem is, I cannot seem to assign this array as the inheritingMembers property of the Member object.

I think you need another return in your recursive function:

function findInheritingMembers($array, $keySearch) {
    foreach ($array as $key => $item){
        if ($key == $keySearch){
            return $item['children'];
        } else {
            if (is_array($item))
                return $this->findInheritingMembers($item, $keySearch);
        }
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM