首先我们要知道 自 PHP 5.3.0 起,php增加了一个叫做 后期静态绑定 的功能,用于在 继承范围内引用静态调用 的类。

 这也导致我们在使用 static 关键词和 self 关键词的时候要特别注意一下,否则很有可能会出现 不可预料 的问题。

1634005785

static 与 self 的不同含义

self 关键词

 调用 取决于定义前方法所在的类 适合我们常规使用逻辑但是它不符合面向对象的设计原则。

static 关键词

 调用 取决于调用当前方法所在的类 更利于实现多态性。

self 和 static 使用测试案例

 首先我们创建两个类非别为 A类B类 其中 B类 继承与 A类,两个类中都定义 test静态方法 其中 A类 定义 self_getstatic_get 方法获取输出 test静态方法 数据用于对比 selfstatic 的不同效果。

self 使用测试案例

class A 
{
    static function test()
    {
        echo "This is class ".__CLASS__;
    }
    static function self_get(){
        self::test();
    }
}
class B extends A
{
    static function test(){
        echo "This is class ".__CLASS__;
    }
}
echo "self---start<br />";
A::self_get();
echo "<br />";
B::self_get();
echo "self---end<br />";
  • self 使用输出结果
self---start
This is class A
This is class A
self---end

static 使用测试案例

class A 
{
    static function test()
    {
        echo "This is class ".__CLASS__;
    }
    static function static_get(){
        static::test();
    }
}
class B extends A
{
    static function test(){
        echo "This is class ".__CLASS__;
    }
}
echo "static---start<br />";
A::static_get();
echo "<br />";
B::static_get();
echo "static---end<br />";
  • static 使用输出结果
static---start
This is class A
This is class B
static---end

 从上面的测试结果可以看出来,不管是 A类 还是 B类 调用 self_get 方法的时候都调用的是 A类 中的 test 方法,而调用使用了后期静态绑定的 static_get 方法的时候调用的当前类的 test 方法。

private 私有方法 static 和 self 使用测试案例

private static function test(){
    echo "This is class ".__CLASS__;
}
  • private 使用输出结果
self---start
This is class A
This is class A
self---end
static--start
This is class A

Fatal error: Uncaught Error: Call to private method B::test() from context 'A' in xxx

 当我们将 test 方法修改为 private 私有方法时发现使用 static 调用的报错了但是使用 self 的不受任何影响。

 好了以上就是详细介绍及分析了 php中使用static与self的不同区别 不过要特别注意下 5.3 以下的 php 版本无法使用 后期静态绑定5.3 以上才可以使用,不过现在大部分都在使用 7.0+ 版本。