How to use the magic method of parent class in subclass

Source: Internet
Author: User
How to use the magic method of the parent class in the subclass? in this post, the parent class: Pclass & nbsp; P {& nbsp; was edited by meenw at 2014-07-2912: 47: 44; & nbsp; private & nbsp; $ name; & nbsp; function & nbsp ;__ how to use the magic method of parent class in subclass

This post was last edited by meenw at 12:47:44 on

Parent class: P

class P{
private $name="";
function __construct(){
$this->name="hello";
}
public function __set($name, $value){
$this->$name=$value;
}
public function showName(){
echo $this->name;
}
}

Subclass: C
Class C extends P {
Function _ construct (){
Parent: :__ construct ();

// How can I change the $ name of the P class here (hello?
}
}


$ C = new C;
$ C-> showName;
Then output: Hello
How to implement it?
------ Solution --------------------
Class P {
Private $ name = "";
Function _ construct (){
$ This-> name = "hello ";
}
Public function _ set ($ name, $ value ){
$ This-> $ name = $ value;
}
Public function showName (){
Echo $ this-> name;
}
}
Class C extends P {
Function _ construct (){
Parent: :__ construct ();
$ This-> name = 'hello ';
}
}
$ C = new C;
$ C-> showName ();

Print_r ($ c );
Hi!
C Object
(
[Name: P: private] => Hello
)

------ Solution --------------------

Class P {
Private $ name = "";
Function _ construct (){
$ This-> name = "hello ";
}
Public function _ set ($ name, $ value ){
$ This-> $ name = $ value;
}
Public function showName (){
Echo $ this-> name;
}
}


Class C extends P {
Function _ construct (){
Parent: :__ construct ();
// How can I change the $ name of the P class here (hello?
$ This-> name = 'hello ';
}
}

$ Obj = new C ();
$ Obj-> showName ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.