php——22-延迟绑定(后期静态绑定) static

本文探讨了在PHP中子类继承父类静态属性和方法时遇到的问题,即子类无法改变父类的静态属性值。通过两个示例,介绍了如何通过重写方法和使用延迟绑定来解决这一问题,确保子类能够正确地覆盖和使用其自己的静态属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用法类似与 self,static::不再被解析为定义当前方法所在的类,而是再实际运行时计算的。比如当一个子类继承了父类的静态属性或方法的时候,它的值并不能被改变,有时不希望看到这种情况。

问题:

当一个子类继承了父类的静态属性或方法的时候,它的值并不能被改变

<?php

class Person
{
    static $name = 'lucy';
    const AGE = 22;

    public static function intro()
    {
        echo 'My name is ' . self::$name . '<br>';
        echo 'My age is ' . self::AGE . '<br>';
    }
}

class Stu extends Person
{
    static $name = 'bob';//无法被调用
}

Person::intro();//My name is lucy //My age is 22
Stu::intro();//My name is lucy //My age is 22
解法一:重写(但是代码很繁琐)
<?php

class Person
{
    static $name = 'lucy';
    const AGE = 22;

    public static function intro()
    {
        echo 'My name is ' . self::$name . '<br>';
        echo 'My age is ' . self::AGE . '<br>';
    }
}

class Stu extends Person
{
    static $name = 'bob';//无法被调用

    public static function intro()
    {
        echo 'My name is ' . self::$name . '<br>';
        echo 'My age is ' . self::AGE . '<br>';
    }
}

Person::intro();//My name is lucy //My age is 22
Stu::intro();//My name is bob //My age is 22
解法二:(延迟绑定)
<?php

class Person
{
    static $name = 'lucy';
    const AGE = 22;

    //延迟绑定函数
    public static function intro1()
    {
        echo 'My name is ' . static::$name . '<br>';
        echo 'My age is ' . static::AGE . '<br>';
    }
}

class Stu extends Person
{
    static $name = 'bob';//无法被调用
}

Person::intro1();//My name is lucy //My age is 22
Stu::intro1();//My name is bob //My age is 22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值