简体   繁体   中英

Appending values from a child class to parent class

I have a file eg class.php with following code:

//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

I need to initiate main_class in main.php file, code of main.php file is as follows

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

later I knew , class sub_class code is wrong , so changed from

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

to

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

but this does not work either , I fail to append values into main_class's output variable so that i can print at last all of logs

You should have to use like this

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

just use the subclass object to get the log.

main class object could not return you any thing due to polymorphism.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM