<div class="codebody" id="code73859"> class People { private $name; public function GetName() { return $this->name; } public function SetName($name) { $this->name=$name; } } class Student extends People { private $grade; public function SayHello() { echo("Good Morning,".parent::GetName()); } }
<div class="codebody" id="code65573"> class Student extends People { public function GetName() { return "kym"; } private $grade; public function SayHello() { echo("Good Morning,".self::GetName()); //echo("Good Morning,".$this->GetName()); } }
<div class="codebody" id="code43547"> <?PHP abstract class People { private $name; public function GetName() { return $this->name; } public function SetName($name) { $this->name=$name; } abstract function SayHello(); } class Student extends People { public function SayHello() { echo("Good Morning,".parent::GetName()); } } $s=new Student(); $s->SetName("kym"); $s->SayHello(); ?>
<div class="codebody" id="code83068"> <?PHP abstract class People { private $name; public function GetName() { return $this->name; } public function SetName($name) { $this->name=$name; } abstract function SayHello(); } interface IRun { function Run(); } class Student extends People implements IRun { public function SayHello() { echo("Good Morning,".parent::GetName()); } public function Run() { echo("两条腿跑"); } } $s=new Student(); $s->SetName("kym"); $s->SayHello(); $s->Run(); ?>
一直忘了说构造方法,其实也就是一段同样的代码: <div class="codetitle"><a style="CURSOR: pointer" data="64505" class="copybut" id="copybut64505" onclick="doCopy('code64505')">代码如下:<div class="codebody" id="code64505"> <?PHP class Person { private $name; private $age; public function Person($name,$age) { $this->name=$name; $this->age=$age; } public function SayHello() { echo("Hello,My name is ".$this->name.".I'm ".$this->age); } } $p=new Person("kym",22); $p->SayHello(); ?>
我们在面试中也许经常会遇到一种变态的题型,就是若干个类之间的关系,然后构造函数呀什么的调来调去。但是,在PHP中就不会遇到这样的情况了,因为在PHP中并不支持构造函数链,也就是说,在你初始化子类的时候,他不会自动去调用父类的构造方法。 <div class="codetitle"><a style="CURSOR: pointer" data="46751" class="copybut" id="copybut46751" onclick="doCopy('code46751')">代码如下:<div class="codebody" id="code46751"> <?PHP class Person { private $name; private $age; public function Person($name,My name is ".$this->name.".I'm ".$this->age); } } class Student extends Person { private $score; public function Student($name,$age,$score) { $this->Person($name,$age); $this->score=$score; } public function Introduce() { parent::SayHello(); echo(".In this exam,I got ".$this->score); } } $s=new Student("kym",22,120); $s->Introduce(); ?>