PHP: how can a class reference its own name?

后端 未结 5 1891
小蘑菇
小蘑菇 2020-12-31 09:27

In PHP, how can a class reference its own name?

For example, what would the method look like to do this?

Dog::sayOwnClassName();
//echos \"Dog\";


        
相关标签:
5条回答
  • 2020-12-31 09:59
    echo get_class($this);
    
    0 讨论(0)
  • 2020-12-31 10:02

    Three options, get_called_class(), get_class() or the magic constant __CLASS__

    Of those three get_called_class() is the one you want when dealing using a static function, although unfortuantely it does have a requirement of a PHP version of at least 5.3.0


    get_called_class()

    If you need to get the class in a static function when the class may be derived it is slightly different as self is resolved to the class name where it was placed (See Limitations of self::). To work around this issue you need to use the function from PHP 5.3.0 get_called_class().

    If you cannot use PHP 5.3.0 or greater you may find you cannot make the function static and still have it achieve the results you want.


    get_class()

    get_class() returns the name of the actual class that the object is, irrespective of where the function call is.

    class Animal{
         public function sayOwnClassName(){
             echo get_class($this);
         }
    }
    
    class Dog extends Animal{
    }
    
    
    $d = new Dog();
    $d->sayOwnClassName(); //echos Dog
    
    $a = new Animal();
    $a->sayOwnClassName(); //echos Animal
    

    get_class can also be used without a parameter, which would at first glance seem to indicate it would with static functions (as there is no need to pass $this), however when used without a parameter it works in the same way as __CLASS__

    class Animal{
         public static function sayOwnClassName(){
             echo get_class();
         }
    }
    
    class Dog extends Animal{
    }
    
    
    Dog::sayOwnClassName(); //echos Animal
    Animal::sayOwnClassName(); //echos Animal
    

    __CLASS__

    __CLASS__ always expands to the name of the class where __CLASS__ was resolved, even when inheritance is taken into account.

    class Animal{
         public function sayOwnClassName(){
             echo __CLASS__; //will always expand to Animal
         }
    }
    
    class Dog extends Animal{
    }
    
    $d = new Dog();
    $d->sayOwnClassName(); //echos Animal
    
    $a = new Animal();
    $a->sayOwnClassName(); //echos Animal
    

    0 讨论(0)
  • 2020-12-31 10:04
    public function sayClassName()
    {
        echo get_class($this);
    }
    

    get_class() php docs

    0 讨论(0)
  • 2020-12-31 10:06

    Well, there's get_class($Object)

    Then there's __CLASS__ when used within a class

    Or you could make a method that would return __CLASS__

    0 讨论(0)
  • 2020-12-31 10:19

    use the magic constant __CLASS__

    0 讨论(0)
提交回复
热议问题