What is the difference between __CLASS__ and get_called_class?

Asked

Viewed 236 times

3

In PHP, I know two methods to display the name of the current class being called: through the magic constant __CLASS__ and function get_called_class().

Apparently, they both do the same thing.

class A 
{
     public static function className()
     { 
          echo get_called_class();
     }  
}


class B
{
     public static function className()
     { 
          echo __CLASS__;
     }  
}


B::className(); // 'B'
A::className(); // 'A'

There is a difference in performance between them?

Is there any difference when calling them?

1 answer

4


Doing the tests after seeing this answer on Soen, they have different effects in situations when we extend a class:

  • get_called_class returns the name of the current class and not where it was declared:

    <?php
    class Foo
    {
        static public function digaMeuNome()
        {
            var_dump(get_called_class());
        }
    }
    
    class Bar extends Foo
    {
    }
    
    Foo::digaMeuNome(); // Retorna Foo
    Bar::digaMeuNome(); // Retorna Bar
    
  • __CLASS__ returns the name of the class where the method was declared, i.e. digaMeuNome was declared in Foo:

    <?php
    class Foo
    {
        static public function digaMeuNome()
        {
            var_dump(__CLASS__);
        }
    }
    
    class Bar extends Foo
    {
    }
    
    Foo::digaMeuNome(); // Retorna Foo
    Bar::digaMeuNome(); // Retorna Foo
    
  • 1

    The answer was a little simple, but I’ll try to complement later.

  • But that’s what I’ve been waiting for :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.