php中new static和new self的区别
作者:admin 日期:2015-07-07
在读Yii2的代码的时候看到的他用了个new static,之前没有用过,所以写了一点代码试了下。差异应该在于new self是实例化当前代码所在类。new static是调用的的那个类,就下面这个例子来说,MyTest继承了Test类, 那么当在MyTest中使用static的时候,这个static代表的就是MyTest,self代表的就是Test。
<?php
class Test {
private $_user;
protected function __construct($user) {
$this->_user = $user;
}
public function showUser(){
echo "{$this->_user}\n";
}
public static function of($user) {
return new static($user);
}
}
class MyTest extends Test{
protected function __construct($user) {
parent::__construct("from MyTest: '.$user);
}
}
class Test2 {
private $_user;
protected function __construct($user) {
$this->_user = $user;
}
public function showUser(){
echo "{$this->_user}\n";
}
public static function of($user) {
return new self($user);
}
}
class MyTest2 extends Test2{
protected function __construct($user) {
parent::__construct('from MyTest: '.$user);
}
}
MyTest::of("hello world")->showUser();
MyTest2::of("hello world")->showUser();
评论: 0 | 查看次数: 14493
订阅
swoole:谁说PHP不支持异步操作?
MySQL:日期函数、时间函数总结(MySQL 5.X)

文章来自:
Tags: