在父类的构造函数中进行了一些运算以及判断。而在子类的构造函数调用了父类的构造函数,那么直接调用子类的任意方法,是不是意味着在父类中的运算以及判断都相当于做了2次呢?如何避免这个问题呢?如果是这样的话,那问题就是大了,比如我判断2个时间差:
$currentime = time();
echo time() - $session['lastdate']; //最后echo出来的会是2个结果,而且后一个结果永远都是0,那这个判断还怎么做?
$currentime = time();
echo time() - $session['lastdate']; //最后echo出来的会是2个结果,而且后一个结果永远都是0,那这个判断还怎么做?
class Parentcls {
/**
* 构造函数
*/
public function __construct(){
$currentime = time();
echo $currentime - $session['lastdate'];
}
}
class Soncls extends Parentcls {
/**
* 构造函数
*/
public function __construct(){
parent::__construct();
}
}class Grandsoncls extends Soncls{
/**
* 构造函数
*/
public function __construct(){
parent::__construct();
$this->show();
}
public function show(){
}
}$obj = new Grandsoncls;
$obj->show();
这样一来出来的会有2个数字,前一个数字是正常的,而最后一个数字永远都是0,我在base类如果进行一些判断是否为0的操作的时候,那么返回的结果都会是条件为0的结果。
$currentime = time();
echo $currentime - $session['lastdate'];
结果
Grandsoncls::show() 方法是空的啊
还有
public function __construct(){
parent::__construct();
$this->show();
}
既然构造函数都用了$this->show();
为什么
$obj = new Grandsoncls;
$obj->show();
这里还要执行一遍$obj->show();
当然你的show函数没有任何计算,所以现在看起来没问题,
如果show函数有计算,必定是计算2次的
protected $islog; public function __construct(){
$this->init();
if($this->islog){
$currentime = time();
echo 'xx';
echo $currentime - $session['lastdate'];
echo 'yy';
}
} private function init(){
$this->islog = checkLog();
} private function checkLog(){
/*过程省略*/
return true;
}
}
class Soncls extends Parentcls {
/**
* 构造函数
*/
public function __construct(){
parent::__construct();
}
}class Grandsoncls extends Soncls{
/**
* 构造函数
*/
public function __construct(){
parent::__construct();
$this->show();
}
public function show(){
}
}$obj = new Grandsoncls;最后运行的结果是xx114yyyxx0yyy我晕,为什么还这样?
应该是你在没写到的某方面重复调用了而且诧异的是 $this->islog = checkLog();会报错,楼主不知道吗Grandsoncls只有一个父类,Soncls。 和Parentcls没有关系。
$this->islog = $this->checkLog();Grandsoncls只有一个父类Soncls没错,那Parentcls又是Soncls的父类,Grandsoncls通过Soncls作为过渡,能不能调用Parentcls类的成员属性呢?
而且Soncls并没有任何实质性改变,即重写方法。因而即使你在Soncls没有定义__construct()方法,
Grandsoncls一样可以通过parent::__construct();访问Parentcls的构造函数话句话说Soncls会自动继承Parentcls的所有方法,且实际上没有改变,因此 Soncls==Parentcls