如果我在 PHP 中扩展一个静态类,并且父类引用“self::”,那么 this 会引用扩展类中的 self 吗?

发布于 2024-09-24 02:52:25 字数 392 浏览 0 评论 0原文

如果我在PHP中扩展一个静态类,并且父类引用“self::”,这会引用扩展类中的self吗?

所以,举例来说,

<?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}
}

如果我跑了 B::猜测(); 然后 B::getVar();

Var 的值是存储在 A::$var 中还是 B::$var 中?

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

余生一个溪 2024-10-01 02:52:25

后期静态绑定是在 PHP 5.3 中引入的,它允许你来控制这种行为。

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

唐婉 2024-10-01 02:52:25

很容易测试:

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'

...希望有帮助:)

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 :)

时光匆匆的小流年 2024-10-01 02:52:25

附加信息,self 或 $this 的使用与扩展类不同

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'

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'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文