PHP: Get the class name passed by var?

I have a function that gets the class passed to it as a parameter. I would like to get the class name of the passed class as a string.

I tried to put this method in a passed class:

function getClassName()
    {
        return __CLASS__;
    }

but if the class is extended, I assumed that it will return the name of the subclass, but it still returns the name of the superclass, which I find odd.

So, if the $ var variable is passed to the function as a parameter, is there a way to get the class name string?

Thank!!

+3
source share
6 answers

See get_class , this should be exactly what you are trying to achieve.

$class_name = get_class($object);
+11
source

:

$class = explode('\\', get_called_class());
echo end($class);

preg_replace

echo preg_replace('/.*([\w]+)$/U', '$1', get_called_class());
+11

__ CLASS __ , .

, :

get_class($param);

In addition, if you use PHP5, Reflection classes are also offered.

+1
source

Use get_class :

$className = get_class($object);
0
source

Straight from php docs: http://uk.php.net/manual/en/function.get-class.php

<?php

abstract class bar {
    public function __construct()
    {
        var_dump(get_class($this));
        var_dump(get_class());
    }
}

class foo extends bar {
}

new foo;

?>

The above example will output:

string(3) "foo"
string(3) "bar"
0
source

you can also add a method to the passed class (s) by returning this:

var_dump (get_called_class ());

0
source

Source: https://habr.com/ru/post/1732869/


All Articles