解析PHP的self关键字
PHP群里有人扣问self
关键字的用途,答案是比力明显的:静态成员函数内不克不及用this
调取非成员函数,但可以用self
调取静态成员函数/变量/常量;其他成员函数可以用self
调取静态成员函数乃至非静态成员函数。随着计议的深入,发明self
并没有那么简便。鉴于此,本文先对几个关键字做对照和区分,再总结self
的用途。
与parent
、static
乃至this
的不同
要想将彻底搞懂self
,要与parent
、static
乃至this
区分开。以下离别做对照。
parent
self
与parent
的区分比力容易: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!", PHP_EOL; } } $base = Child::getSelf(); $child = Child::getInstance(); $child->selfFoo(); $child->staticFoo(); $child->thisFoo();
程序输出结果如下:
Base constructor! Child constructor! Base Foo! Child Foo! Child Foo!
在函数援用上,self
与static
的不同是:关于静态成员函数,self
指向代码当前类,static
指向调取类;关于非静态成员函数,self
按捺多态,指向当前类的成员函数,static
等同于this
,动态指向调取类的函数。
parent
、self
、static
三个关键字结合在一起看挺成心思,离别指向父类、当前类、子类,有点“过去、此刻、将来”的味道。
this
self
与this
是被计议最多,也是最容易引发误用的组合。两者的主要不同如下:
this
不克不及用在静态成员函数中,self
可以;- 对静态成员函数/变量的拜访,倡议 用
self
,不要用$this::
或$this->
的情势; - 对非静态成员变量的拜访,不克不及用
self
,只能用this
; this
要在对象已经实例化的状况下使用,self
没有此限制;- 在非静态成员函数内使用,
self
按捺多态行动,援用当前类的函数;而this
援用调取类的重写(override)函数(假如有的话)。
self
的用处
看完与上述三个关键字的不同,self
的用处是不是呼之即出?一句话总结,那就是:self
总是指向“当前类(及类实例)”。具体说则是:
- 替换类名,援用当前类的静态成员变量和静态函数;
- 按捺多态行动,援用当前类的函数而非子类中覆盖的实现;
槽点
- 这几个关键字中,只要
this
要加$
符号且必需加,强迫症表示很难受; - 静态成员函数中不克不及通过
$this->
调取非静态成员函数,但是可以通过self::
调取,且在调取函数中未使用$this->
的状况下还能顺畅运转。此行动貌似在不一样PHP版本中展现不一样,在当前的7.3中ok; - 在静态函数和非静态函数中输出
self
,猜猜结果是啥?都是string(4) "self"
,迷之输出; return $this instanceof static::class;
会有语法错误,但是以下两种写法就正常:$class = static::class; return $this instanceof $class; // 或者这样: return $this instanceof static;
所以这是为什么啊?!
更多PHP相关技术文章,请拜访PHP教程栏目停止学习!
以上就是解析PHP的self关键字的具体内容,更多请关注百分百源码网其它相关文章!