Is it possible to get the name of the top level class from an extended class, without setting it from the top level class. See example below, I would like to get 'Foo' from Base. I know I could set a variable from Foo, but hoping to skip the extra step.
Thanks.
class Base {
function __construct() {
echo '<p>get_class: '.get_class().'</p>';
echo '<p>__CLASS__: '.__CLASS__.'</p>';
}
}
class Foo extends Base {
}
$test = new Foo();
(PHP 5.2.4+)
A subclass is a class that “extends” an existing class; that is, it has the attributes and methods of the existing class, plus more.
The Class object has a getName() method that returns the name of the class. So your displayClass() method can call getClass(), and then getName() on the Class object, to get the name of the class of the object it finds itself in.
The parent() method is used to return all ancestor of the selected elements. Check if ancestor (parent) class exist then it returns the class name otherwise returns not exist.
PHP | get_class() Function The get_class() function is an inbuilt function in PHP which is used to return the class name of an object. Syntax: string get_class( object $object ) Parameters: This function accepts single parameter $object which holds the object that need to be tested.
Use:
get_class($this);
get_called_class()
for static classes or get_class($this)
for instantiated.
get_called_class()
, as Jason said, was introduced in PHP 5.3
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