[php]通过单例模式看self,static,$this的区别

单例模式比较简单,下面是一种写法:

    public static function getInstance() {
        static $i = null;  //注:声明时不能是函数或者计算
        (is_null($i)) && ($i = new static());
        return $i;
    }

这里想说new static() 和 self()的区别
官方资料这样写:
self refers to the same class in which the new keyword is actually written.
static, in PHP 5.3’s late static bindings, refers to whatever class in the hierarchy you called the method on.
self是当前类,而static取决你调用方法的层次
例子如下:

class A {
    public static function className(){
        echo __CLASS__;
    }

    public static function test(){
        self::className();
    }
}

class B extends A{
    public static function className(){
        echo __CLASS__;
    }
}

B::test();  //A
class A {
    public static function className(){
        echo __CLASS__;
    }

    public static function test(){
        static::className();
    }
}

class B extends A{
    public static function className(){
        echo __CLASS__;
    }
}
B::test(); //B

对于$this 和self
this是指向当前对象的指针,self是指向当前类的指针
也有网友这样总结:
Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.
只要注意在静态函数或者静态变量上的使用,就能应对一般的问题

发表评论

电子邮件地址不会被公开。 必填项已用*标注


*