When to use self over $this?

前端 未结 23 2862
醉梦人生
醉梦人生 2020-11-21 11:19

In PHP 5, what is the difference between using self and $this?

When is each appropriate?

23条回答
  •  面向向阳花
    2020-11-21 12:21

    Additionally since $this:: has not been discussed yet.

    For informational purposes only, as of PHP 5.3 when dealing with instantiated objects to get the current scope value, as opposed to using static::, one can alternatively use $this:: like so.

    http://ideone.com/7etRHy

    class Foo
    {
        const NAME = 'Foo';
    
        //Always Foo::NAME (Foo) due to self
        protected static $staticName = self::NAME;
    
        public function __construct()
        {
            echo $this::NAME;
        }
    
        public function getStaticName()
        {
           echo $this::$staticName;
        }
    }
    
    class Bar extends Foo
    {
        const NAME = 'FooBar';
    
        /**
         * override getStaticName to output Bar::NAME
         */
        public function getStaticName()
        {
            $this::$staticName = $this::NAME;
            parent::getStaticName();
        }
    }
    
    $foo = new Foo; //outputs Foo
    $bar = new Bar; //outputs FooBar
    $foo->getStaticName(); //outputs Foo
    $bar->getStaticName(); //outputs FooBar
    $foo->getStaticName(); //outputs FooBar
    

    Using the code above is not common or recommended practice, but is simply to illustrate its usage, and is to act as more of a "Did you know?" in reference to the original poster's question.

    It also represents the usage of $object::CONSTANT for example echo $foo::NAME; as opposed to $this::NAME;

提交回复
热议问题