PHP面向对象self 和parent讲解
/*
* 总结self,parent的用法
*
* self:本类,自身(不要理解为本对象)
* parent:父类
*
* 在引入自身的静态属性/静态方法以及父类的方法时,可以用到
*
* 用法:
* self::$staticProperty
* self::staticMothed;
* parent::$staticProperty
* parent::Mothed;
*/
/* class Human {
static public $head='php';
public function say() {
echo Human::$head,'<br />';
}
}
echo Human::$head,'<br />';
$jun=new Human();
echo $jun->say(); */
//某一天类名要统一,规范化,Human不叫Human了,叫wHuman
//导致内部,凡引用到自身类名的也要改
class wHuman {
static public $head='php2';
function say() {
echo self::$head,'<br />';
}
}
echo wHuman::$head,'<br />';
$jun=new wHuman();
echo $jun->say();
class Man extends wHuman {
static public $head='php3';
public function say() {
echo self::$head,'<br />';
echo parent::$head,'<br />';
}
}
$lan=new Man();
echo $lan->say(); //php3,php2
//经典例子:
class a {
public function a1() {
echo 'this is function a1';
}
}
class b extends a {
public function b1() {
echo $this->a1();
}
public function b2() {
echo parent::a1();
}
}
$a1=new b();
echo $a1->b1(),'<br />';
echo $a1->b2(),'<br />';
/*
* 上面两个调用echo 出来的效果是一样的
* 如果从速度角度看,理论上parent::稍微快一点点
* 因为在子类寻找a1方法,寻找不到,再去其父类寻找
*
* 但是从面向对象角度看,继承过来的,就是自己的
* $this 更符合面向对象的思想
*
* 举个反利
class a {
}
class b extends a{
}
class c extends b{
}
...
...
class f extends e {
parent::parent::parent::...
很明显这样写是不人性化的
}
*/
Dcr163的博客
http://dcr163.cn/31.html(转载时请注明本文出处及文章链接)