Last Updated:

PHP : Get the namespace of the child class using the parent class method

parent class method in php

 
 
Let's imagine a situation where we create an instance of a child class that inherits from the parent class. Refer to a method of a child class that is actually inherited from the parent class. And this method should return the namespace of the child class.
 


Let's take a closer look at the task:
Code of the Start file.php and the Child Class Start contained in it:


As you can see, we have no methods at all in the child class. But method 1 (index) inherits from the parent class.

The code of the ParentStart file.php and the contained code of the parent class:


Now, having created and accessed an instance of the Start class, we can call the method (index) contained in the parent class.



At this point, this code won't return anything to us because the body of the parent class's method is empty.

Let's determine that this method should return us a string of the namespace of the child class.
Perhaps someone will say, well, what can be difficult here. You need to write something like this and everything will be cool:


But this code will return a path string to the namespace of the parent class, not the child.

The following line will be returned:
<?php namespace app\Components\Registration;

class Start extends \app\Components\ParentStart {}
<?php namespace app\Components;

abstract class ParentStart
{
    public function index() {

    }
}
$start = new Start();

$start->index();
<?php namespace app\Components;

abstract class ParentStart
{
    public function index() {
        return (string)__NAMESPACE__;
    }
}

app\Components


The following solution to the problem was found:
The path of the called class was obtained and the name of this class was removed from this path.


The total code looks like this:


A child class string will be returned:

The string we needed.
substr(get_called_class(), 0, strrpos(get_called_class(), "\\"))
<?php namespace app\Components;

abstract class ParentStart
{
    public function index() {
        return (string)substr(get_called_class(), 0, strrpos(get_called_class(), "\\"));
    }
}

app\Components\News


Perform validation:



This will return a string containing the namespace of the child class:
$start = new Start();

var_dump($start->index());

app\Components\News