一旦工作,那就要努力的干,聪明的干,快速的干——用省下来的时间干自己喜欢干的事情。!

php中self::可以访问实例方法,不能访问实例变量,self::和$this的区别

php lampnick 2476℃ 0评论

refer:http://php.net/manual/zh/language.oop5.paamayim-nekudotayim.php
In PHP, you use the self keyword to access static properties and methods.

The problem is that you can replace $this->method() with self::method() anywhere, regardless if method() is declared static or not. So which one should you use?

Consider this code:

<?php
class ParentClass {
    public $foo = 'test';
    public function test() {
        self::who();    // will output 'parent'
        $this->who();    // will output 'child'
        echo $this->foo; //will output 'test'
        echo self::$foo; //will throw Fatal error: Access to undeclared static property: ParentClass::$foo in *.php
    }
     public function who() {
         echo 'parent';
     }
}
class ChildClass extends ParentClass {
    public function who() {
        echo 'child';
    } 
}
$obj = new ChildClass();
$obj->test();

In this example, self::who() will always output ‘parent’, while $this->who() will depend on what class the object has.

Now we can see that self refers to the class in which it is called, while $this refers to the class of the current object.

So, you should use self only when $this is not available, or when you don’t want to allow descendant classes to overwrite the current method.

此上可知:

self::可以访问父类和子类的方法,如有有父类的时候,则访问的是父类的。$this则是访问的当前对象的方法。

转载请注明:MitNick » php中self::可以访问实例方法,不能访问实例变量,self::和$this的区别

喜欢 (5)or分享 (0)
头像
发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址