PHP的self和static区别

1,095 阅读1分钟

在学PHP的面向对象中,我们经常都会遇到静态变量和静态方法,我们都知道使用在一个类中都可以使用self或者static来调用,但是两者还是有很明显的区别,下面来看两段代码就清楚了。

<?php

/**
 * self demo
 */
class SelfDemo
{
    public static function model()
    {
        self::getModel();
    }

    protected static function getModel()
    {
        echo "self model". "<br>";
    }
}

SelfDemo::model();

class SelfDemoExtend extends SelfDemo
{
    protected static function getModel()
    {
        echo "self extend model" . "<br>";
    }
}

SelfDemoExtend::model();

执行结果如下:
self model
self model

<?php

/**
 * static demo
 */
class StaticDemo
{
    public static function model()
    {
        static::getModel();
    }

    protected static function getModel()
    {
        echo "static model" . "<br>";
    }
}
    StaticDemo::model();

class StaticDemoExtend extends StaticDemo
{
    protected static function getModel()
    {
        echo "static extend model" . "<br>";
    }
}

StaticDemoExtend::model();

执行结果如下:
static model
static extend model

从上面的两个例子可以很明显的看出,self和static的区别,其区别主要是self只能引用当前类,说白了就是self在哪个类,就引用那个类,而static关键字能够允许在运行时动态绑定类方法,在调用static,子类哪怕调用的是父类的方法,但是父类方法中调用的方法还会是子类的方法