• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

解析PHP的self关键字

php 搞代码 4年前 (2022-01-21) 25次浏览 已收录 0个评论

PHP群里有人询问self关键字的用法,答案是比较明显的:静态成员函数内不能用this调用非成员函数,但可以用self调用静态成员函数/变量/常量;其他成员函数可以用self调用静态成员函数以及非静态成员函数。随着讨论的深入,发现self并没有那么简单。鉴于此,本文先对几个关键字做对比和区分,再总结self的用法。

parentstatic以及this的区别

要想将彻底搞懂self,要与parentstatic以及this区分开。以下分别做对比。

parent

selfparent的区分比较容易:parent引用父类/基类被隐盖的方法(或变量),self则引用自身方法(或变量)。例如构造函数中调用父类构造函数:

class Base {    public function __construct() {        echo "Base contructor!", PHP_EOL;    }}class Child {    public function __construct() {        parent::__construct();        echo "Child contructor!", PHP_EOL;    }}new Child;// 输出:// Base contructor!// Child contructor!

static

static常规用途是修饰函数或变量使其成为类函数和类变量,也可以修饰函数内变量延长其生命周期至整个应用程序的生命周期。但是其与self关联上是PHP 5.3以来引入的新用途:静态延迟绑定。

有了static的静态延迟绑定功能,可以在运行时动态确定归属的类。例如:

class Base {    public function __construct() {        echo "Base constructor!", PHP_EOL;    }    public static function getSelf() {        return new self();    }    public static function getInstance() {        return new static();    }    public function selfFoo() {        return self::foo();    }    public function staticFoo() {        return static::foo();    }    public function thisFoo() {        return $this->foo();    }    public function foo() {        echo  "Base Foo!", PHP_EOL;    }}class Child extends Base {    public function __construct() {        echo "Child constructor!", PHP_EOL;    }    public function foo() {        echo "Child Foo!", PH<b style="color:transparent">来&源gao@dai!ma.com搞$代^码%网</b><img>搞gaodaima代码</img>P_EOL;    }}$base = Child::getSelf();$child = Child::getInstance();$child->selfFoo();$child->staticFoo();$child->thisFoo();

程序输出结果如下:

Base constructor!Child constructor!Base Foo!Child Foo!Child Foo!

在函数引用上,selfstatic的区别是:对于静态成员函数,self指向代码当前类,static指向调用类;对于非静态成员函数,self抑制多态,指向当前类的成员函数,static等同于this,动态指向调用类的函数。

parentselfstatic三个关键字联合在一起看挺有意思,分别指向父类、当前类、子类,有点“过去、现在、未来”的味道。

this

selfthis是被讨论最多,也是最容易引起误用的组合。两者的主要区别如下:

  1. this不能用在静态成员函数中,self可以;
  2. 对静态成员函数/变量的访问,建议self,不要用$this::$this->的形式;
  3. 对非静态成员变量的访问,不能用self,只能用this;
  4. this要在对象已经实例化的情况下使用,self没有此限制;
  5. 在非静态成员函数内使用,self抑制多态行为,引用当前类的函数;而this引用调用类的重写(override)函数(如果有的话)。

self的用途


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:解析PHP的self关键字

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

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

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