开发者

If i extend a static class in PHP, and the parent class refers to "self::", will this refer to the self in the extended class?

开发者 https://www.devze.com 2023-01-16 03:39 出处:网络
If i extend a static class in PHP, and the parent class refers to \"self::\", will this refer to the self in the extended class?

If i extend a static class in PHP, and the parent class refers to "self::", will this refer to the self in the extended class?

So, for example

<?php 
Class A
{
    static $var  
    public static function guess(){self::$var = rand(); return $var}
}        

Class B extends Class A
{
    public static function getVar(){return self::$var开发者_开发知识库}
}

If I ran B::guess(); then B::getVar();

is the value for Var stored in A::$var or B::$var?

Thank you.


Late static binding was introduced in PHP 5.3, it allows you to control this behavior.


It's easy to test:

class ClassA {
    public static function test(){ self::getVar(); }
    public static function getVar(){ echo 'A'; }
}        

class ClassB extends ClassA {
    public static function getVar(){ echo 'B'; }
}

ClassA::test(); // prints 'A'

ClassB::test(); // also prints 'A'

... hope that helps :)


Additional information, usage of self or $this is different into extended classes

class ClassA {
    public function test(){ self::getVar(); }
    public function test2(){ $this->getVar(); }
    
    public function getVar(){ echo 'A'; }
}        

class ClassB extends ClassA {
    public function getVar(){ echo 'B'; }
}

$classB = new ClassB();
$classB->test(); // prints 'A'
$classB->test2(); // prints 'B'
0

精彩评论

暂无评论...
验证码 换一张
取 消