简述php钟static和self的区别
简述php钟static和self的区别
关于static和self的指示对象
class A{
public function test_self(){
return new self();
}
public function test_static(){
return new static();
}
}
class B extends A{
}
$b = new B;
$self = $b->test_self();
$static = $b->test_static();
var_dump($self);
var_dump($static);
结果是:
D:\wamp\www\b.php:16:
object(A)[2]
D:\wamp\www\b.php:17:
object(B)[3]
也就是是说self指定的对象是当前定义所属的类,而且static则是具体实例化后所属的类。
下面在看一种情况,如果子类rewrite了父类的方法呢?
class A{
public function test_self(){
return new self();
}
public function test_static(){
return new static();
}
}
class B extends A{
public function test_self(){
return new self();
}
public function test_static(){
return new static();
}
}
$b = new B;
$self = $b->test_self();
$static = $b->test_static();
var_dump($self);
var_dump($static);
结果是
D:\wamp\www\b.php:21:
object(B)[2]
D:\wamp\www\b.php:22:
object(B)[3]
结果与上述一致。。。。