Radek Simko
Radek Simko

Reputation: 16146

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.

Upvotes: 5

Views: 2431

Answers (2)

KingCrunch
KingCrunch

Reputation: 132071

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

Upvotes: 8

user142162
user142162

Reputation:

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

Upvotes: 5

Related Questions