将子类中的值附加到父类

时间:2015-10-02 10:22:26

标签: php oop

我有一个文件,例如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的输出变量中,以便我可以在最后打印所有日志

1 个答案:

答案 0 :(得分:1)

你应该像这样使用

$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;

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

由于多态性,

主类对象无法返回任何东西。