You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用$this调用静态属性是否可行?为何下述代码能正常运行?

为什么$this::能调用类静态属性?

首先要澄清:PHP允许使用$this::访问静态属性/方法,这完全是合法的语法,并不是错误用法。

$this::的作用是基于当前对象的实际所属类(运行时类)来获取静态成员,效果和static::类似,但它是通过对象实例触发的。比如如果有子类继承原类并重写了静态属性,用$this::会拿到子类的属性值,而self::只会取当前代码所在类的属性:

class Test 
{
    public static string $test = 'test';

    public function it(): void
    {
        echo $this::$test . "\n";
        echo self::$test . "\n";
    }
}

class ChildTest extends Test
{
    public static string $test = 'child test';
}

(new ChildTest())->it();
// 输出结果:
// child test
// test

你看到的代码能正常运行,就是因为PHP本身支持这种语法,它属于后期静态绑定的一种场景,用来通过对象实例访问其所属类的静态成员。只是日常开发里更推荐用self::或static::来明确静态成员的访问方式,但$this::本身是有效的。

内容的提问来源于stack exchange,提问作者user3548997

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:22:32