将子类的值附加到父类


Appending values from a child class to parent class

我有一个文件,例如class.php与以下代码:

//class.php 
class main_class { 
public $output;
public function print_me ( $msg ){
$this->output .= $msg.''r'n' ;
}
//….
//….
//more functions
// some of them using this->print_me 
} 
class sub_class extends main_class { 
function verification (){ 
this->print_me ( 'Log: while verification' );
}
}
//class.php ends

我需要在main.php文件中初始化main_class, main.php文件代码如下

 //main.php 
require 'class.php';
    $main_class = new main_class();
    //and need to append values into output variables
$main_class->print_me ( 'Log: from main.php ' );
//but before echoing , I need to initiate sub class as follows:
//$sub_class = new $sub_class();
//though I do not need to append/ values using $sub_class instance , 
//I need to append value from within the class itself at last I can print output variable e.g. 
echo $main_class->output;

后来我知道,类sub_class的代码是错误的,所以从

改为
function verification (){ 
this->print_me ( 'Log: while verification' );
}

function verification (){ 
parent::print_me ( 'Log: while verification' );
}

,但这也不起作用,我没有将值附加到main_class的输出变量中,这样我就可以打印最后所有的日志

你应该像这样使用

$sub_class = new sub_class();
$sub_class->verification ( 'Log: from main.php 1 ' );
$sub_class->verification ( 'Log: from main.php 2 ' );
echo $sub_class->output;

只使用子类对象来获取日志。

主类对象由于多态性不能返回任何东西