简体   繁体   中英

accessing a child class prop from parent

I mean something like that:

class parentClass {
    public function method() {
        echo $this->prop;
    }
}
class childClass extends parentClass {
    public $prop = 5;
}

How can I get a child prop from the parent prop?

Thanks...

Either I don't fully understand what you want or the solution is as trivial as the following code.

class parentClass {
    public function method() {
        echo $this->prop;
    }
}
class childClass extends parentClass {
    public $prop = 5;
}
$object = new childClass();
$object->method();

I mean the child class is extending the base class which means it will also inherit all the methods of its parent's class. That makes the whole process of using the parent's class method as simple as calling it from the instance of the child class.

All protected and public members of child classes are visible from within their parent class in PHP, so the example code you provided should work just fine. Quote from the php doc :

Members declared protected can be accessed only within the class itself and by inherited and parent classes.

But the actual question is: do you really need it?

The proper OO way would be to define a self-contained parent class that expresses something. It should not need to access properties of child classes - this is a so-called code smell . If you really think that you have a case where a similar construct is necessary, you are probably looking for abstract methods, which guarantee that every child class has this property:

abstract class Animal {
    public function makeNoise() {
        echo $this->getNoiseString();
    }
    protected abstract function getNoiseString();
}

class Cat extends Animal {
    protected function getNoiseString() {
        return 'meow';
    }
}
//parent
class parentClass {

    protected $prop = null;

    public function method() {
        echo $this->prop;
    }
}

//child
class childClass extends parentClass {
    protected $prop = 5;
}

Make sure the variable is defined in the parentclass as well. So it will be accessible by the parent.

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