php - 将子类的值附加到父类

标签 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;

后来才知道,class 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;

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

由于多态性,主类对象无法返回任何东西。

关于php - 将子类的值附加到父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32905158/

相关文章:

php - Laravel 5 中的 After Validation Hook 有什么用

php - 推送通知 iphone(我的设备没有收到通知)

java - 最小的 API 与便利

c++ - 返回默认构造值有什么问题吗?

c++ - 派生值或附加属性的方法?

php - mysql 查询 2 个表的总和

PHP自动分配查询字符串变量而无需我做任何事情

c++ - 如何在类构造函数中初始化数组?

php - 使用 PHP 的 OOD 与基于功能服务的架构

php - 一条mysql语句的两个结果