Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class name from static child method

<?php
class MyParent {

    public static function tellSomething() {
        return __CLASS__;
    }
}

class MyChild extends MyParent {

}

echo MyChild::tellSomething();

The code above echos "MyParent". How can i get to name of child class - in this case "MyChild"? If it's possible...

I just simply need to know which child is calling the inherited method.

like image 936
Radek Simko Avatar asked Jun 29 '11 13:06

Radek Simko


2 Answers

__CLASS__ is a pseudo-constant, that always refers to the class, where it is defined. With late-static-binding the function get_called_class() were introduced, that resolve the classname during runtime.

class MyParent {

  public static function tellSomething() {
    return get_called_class();
  }
}

class MyChild extends MyParent {

}

echo MyChild::tellSomething();

(as a sidenote: usually methods don't need to know the class on were they are called)

like image 62
KingCrunch Avatar answered Oct 01 '22 08:10

KingCrunch


What you are describing is called Late Static Bindings, and it was made available in PHP 5.3.

like image 21
Tim Cooper Avatar answered Oct 01 '22 09:10

Tim Cooper