What is the difference between __CLASS__ and get_called_class?

3

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

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'

Is there a performance difference between them?

Is there a difference in calling them?

    
asked by anonymous 31.03.2016 / 19:08

1 answer

4

Performing the tests after seeing this answer in SOen , they have different effects on 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, ie the digaMeuNome method 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
    
31.03.2016 / 19:40