topherg
topherg

Reputation: 4293

Getting class name from static function in abstract class

I have an abstract class that has a number of static functions (which return a new instance of itself by using new static($args) which works fine), but I can't work out how to get the class name. I am trying to avoid putting

protected static $cn = __CLASS__;

but if unavoidable, then its not the end of the world

abstract class ExtendableObject {
    static function getObject() {
        return new static($data);
    }

    static function getSearcher() {
        return new ExtendableObjectFinder(/* CLASS NAME CLASS */);
    }
}

class ExtendableObjectFinder {
    private $cn;

    function __construct($className) {
       $this->cn = $className;
    }

    function where($where) { ... }

    function fetch() { ... }
}

Upvotes: 4

Views: 3457

Answers (2)

Brad Christie
Brad Christie

Reputation: 101604

To get the name of the class you can use get_class and pass $this.

Alternatively, there is get_called_class which you can use within static methods.

Upvotes: 4

alex
alex

Reputation: 490153

You don't need to use the class name explicitly, you can use self.

class SomeClass {

    private static $instance;

    public static function getInstance() {

          if (self::$instance) {
               // ...
          }

    }

}

CodePad.

Upvotes: 0

Related Questions