PHP parent function not able to see subclass membe

2019-05-01 23:26发布

I would like to have my abstract parent class have a method that would be inherited by a subclass which would allow that subclass to iterate through all of it's variables (both the variables inherited from the parent, and it's own variables).

At the moment if I implement this method in the parent, then only the parent's variables will be iterated over:

class MyObject {

    private $one;
    private $two;
    private $three;

    function assignToMembers() {
        $xx = 1;
        foreach($this as $key => $value) {
            echo "key: ".$key."<br />";
            $this->$key = $xx;
            $xx++;
        }
    }

    public function getOne() {
        return $this->one;
    }

    public function getTwo() {
        return $this->two;
    }

    public function getThree() {
        return $this->three;
    }
}


class MyObjectSubclass extends MyObject {

    private $four;
    private $five;

    public function getFour() {
        return $this->four;
    }

    public function getFive() {
        return $this->five;
    }
}
$o = new MyObjectSubclass();
$o->assignToMembers();
echo $o->getOne()." ";
echo $o->getTwo()." ";
echo $o->getThree()." ";
echo $o->getFour()." ";
echo $o->getFive()." ";

// This prints 1 2 3

On the other hand, if I put the assignToMembers function in the subclass, then only the subclass's members are iterated over.

Because I want my assignToMembers() function to be usable by a number of subclasses, I don't want to have to implement it in every one, only in the parent class, but it looks like I will have to unless it can access that class's members.

Is there any way to acheive this?

Thanks in advance.

标签: php oop
3条回答
我只想做你的唯一
2楼-- · 2019-05-01 23:51

It appears to be an issue with visibility.

In your child class, changing private to protected allows the parent to access the child's properties.

For more detailed information, see: http://us2.php.net/manual/en/language.oop5.visibility.php

查看更多
来,给爷笑一个
3楼-- · 2019-05-01 23:57

You'll need to use protected if you want your code to work as described. Remember the roles of the access/visibility modifiers:

  • private - class level only access
  • protected - whole inheritance chain access
  • public - universal access
查看更多
姐就是有狂的资本
4楼-- · 2019-05-02 00:05

Try changing your "private" definitions to "protected" ones.

PHP Visibility:

Visibility

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

查看更多
登录 后发表回答