我们继续上一节中的例子,在PHP中,继承和Java是一样的,都使用extends关键字。 复制代码 代码如下: 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()); } }
如果我们要访问自身的方法,那么可以用this,也可以用self。 复制代码 代码如下: class Student extends People { public function GetName() { return "kym"; } private $grade; public function SayHello() { echo("Good Morning,".self::GetName()); //echo("Good Morning,".$this->GetName()); } }
2. 抽象类
提到继承,就不得不说抽象类。 复制代码 代码如下: <?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(); ?>
3. 接口
接下来就是接口: 复制代码 代码如下: <?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(); ?>
都没什么好说的,跟Java一模一样。
4. 构造方法
一直忘了说构造方法,其实也就是一段同样的代码: 复制代码 代码如下: <?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中并不支持构造函数链,也就是说,在你初始化子类的时候,他不会自动去调用父类的构造方法。 复制代码 代码如下: <?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); } } 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(); ?>
5. 析构函数
析构函数和C#和C++中不同,在PHP中,析构函数的名称是__destructor()。 复制代码 代码如下: 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); } function __destruct() { echo("我要被卸载了"); } }