Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get parent extends class in php

i have the oop php code:

class a {
    // with properties and functions
}

class b extends a {
    public function test() {
        echo __CLASS__; // this is b
        // parent::__CLASS__ // error
    }
}

$b = new b();
$b->test();

I have a few parent class (normal and abstract) and many child classes. The child classes extend the parent classes. So when I instantiate the child at some point I need to find out what parent I called.

for example the function b::test() will return a

How can I get (from my code) the class a from my class b?

thanks

like image 384
ana Avatar asked Nov 26 '11 14:11

ana


People also ask

What is parent :: in PHP?

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.

What is the purpose of $this in PHP?

$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.

How can I inherit in PHP?

Inheritance in OOP = When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword.

Can PHP class extend two classes?

Classes, case classes, objects, and traits can all extend no more than one class but can extend multiple traits at the same time.


1 Answers

Your code suggested you used parent, which in fact is what you need. The issue lies with the magic __CLASS__ variable.

The documentation states:

As of PHP 5 this constant returns the class name as it was declared.

Which is what we need, but as noted in this comment on php.net:

claude noted that __CLASS__ always contains the class that it is called in, if you would rather have the class that called the method use get_class($this) instead. However this only works with instances, not when called statically.

If you only are in need of the parent class, theres a function for that aswell. That one is called get_parent_class

like image 143
Jan Dragsbaek Avatar answered Oct 07 '22 18:10

Jan Dragsbaek