Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jlrdw's avatar
Level 75

PHP general question

At times in a helper class I have something like:

 protected static $instance;
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }

It's always worked. But recently I ran across this:

 protected static $instance;
        $myClass = get_called_class();
        self::$instance = new $myClass;

I have never used get_called_class(), both work. Is one better than the other.

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

They do have different outcomes in the case where you are having a class that inherits from this class; same as if you replace new self() with new static()

jlrdw's avatar
Level 75

No Inheritance, and no extends used. So would the examples I gave work the same, or which would you use?

I was basically re-writing an old paginator, and looking for ideas. Saw example here:

https://github.com/yidas/php-pagination

tykus's avatar

For me, new static every time - get_called_class is effectively doing the same thing, i.e. getting the class name from the late static bound class. And it allows the class to be extended relatively easily

Please or to participate in this conversation.