Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class name from extended class

Tags:

oop

php

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+)

like image 836
Louis W Avatar asked Jul 31 '09 20:07

Louis W


People also ask

Which is the name of the class you have to extend?

A subclass is a class that “extends” an existing class; that is, it has the attributes and methods of the existing class, plus more.

How do you find the class name for a subclass?

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.

How do I find parent class names?

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.

What is get_ class in PHP?

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.


2 Answers

Use:

get_class($this);
like image 88
Ionuț G. Stan Avatar answered Oct 25 '22 19:10

Ionuț G. Stan


get_called_class() for static classes or get_class($this) for instantiated.

get_called_class(), as Jason said, was introduced in PHP 5.3

like image 39
Tyler Carter Avatar answered Oct 25 '22 20:10

Tyler Carter