I search a way to access to the parent, parent function of a class without to call the parent... Hmmm, that sound a bit weird explanation so i will give an example:
class myclass { public function test() { return 'level 1'; } } class myclass2 extends myclass { public function test() { return parent::test() . '-level 2'; } } class myclass3 extends myclass2 { public function test() { return parent::test() . '-level 3'; } } $example = new myclass3(); echo $example->test(); // should display "level 1-level 2-level 3"
I would like to display "level 1-level 3" then doing something like that:
class myclass3 extends myclass2 { public function test() { return parent::parent::test() . '-level 3'; } }
Do you have an idea how I can do this? (I am not allow to edit myclass and myclass2, they are part of a framework...)
parent:: is the special name for parent class which when used in a member function.To use the parent to call the parent class constructor to initialize the parent class so that the object inherits the class assignment to give a name. NOTE: PHP does not accept parent as the name of a function.
$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods.
We can't run directly the parent class constructor in child class if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
Simple solution. Use the root object myclass directly:
class myclass3 extends myclass2 { public function test() { return myclass::test() . '-level 3'; } }
If you need a more general approach have a look at outis answer.
You could do it using get_parent_class
function get_grandparent_class($thing) { if (is_object($thing)) { $thing = get_class($thing); } return get_parent_class(get_parent_class($thing)); } class myclass3 extends myclass2 { public function test() { $grandparent = get_grandparent_class($this); return $grandparent::test() . '-level 3'; } }
Or you could use reflection:
function get_grandparent_class($thing) { if (is_object($thing)) { $thing = get_class($thing); } $class = new ReflectionClass($thing); return $class->getParentClass()->getParentClass()->getName(); }
However, it may not be a good idea, depending on what you're trying to achieve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With