PHP笔记-面向对象之继承(构造方法篇)

作者:聂勇 欢迎转载,请保留作者信息并说明文章来源!

前一篇文章讲了构造方法定义时有趣的问题,这篇文章还是继续讲构造方法,但讲的是它的继承问题。PHP5的类的实例初始化与JAVA存在不同,差异在哪里,通过一个测试来说明。

一、父类源代码 | Parent class source

父类源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
class People {
private $name;
private $age;
function __construct() {
echo "call construct method '__construct'";
$this->age=20;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setAge($age) {
$this->age = $age;
}
public function getAge() {
return $this->age;
}
}
?>

二、无自定义构造方法的子类 | Subclass has no custom constructor

1、无自定义构造方法的子类源代码:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
require "/home/nieyong/local/nginx-0.7.68/html/object/Pepole.php";
class Man extends People {
private $sex;
public function getSex() {
return $this->sex;
}
}
?>

2、执行:

1
2
3
4
5
6
7
8
9
10
<?php
require '/home/aofeng/local/nginx-0.7.68/html/object/Man.php';
$man = new Man();
?>
<br/>
People Information:<br/>
name:<?php echo $man->getName();?><br/>
age:<?php echo $man->getAge();?><br/>
sex:<?php echo $man->getSex();?><br/>

输出:

call construct method ‘__construct’
People Information:
name:
age:20
sex:

三、有自定义构造方法的子类 | Subclass has custom constructor

1、有自定义构造方法的子类源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
require "/home/nieyong/local/nginx-0.7.68/html/object/Pepole.php";
class Man extends People {
private $sex;
function __construct() {
$this->sex = "M";
}
public function getSex() {
return $this->sex;
}
}
?>

说明:

  • 多了一个自定义的构造方法。

2、执行:

1
2
3
4
5
6
7
8
9
10
<?php
require '/home/aofeng/local/nginx-0.7.68/html/object/Man.php';
$man = new Man();
?>
<br/>
People Information:<br/>
name:<?php echo $man->getName();?><br/>
age:<?php echo $man->getAge();?><br/>
sex:<?php echo $man->getSex();?><br/>

输出:

People Information:
name:
age:
sex:M

3、修正Man的代码,新的源代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
require "/home/nieyong/local/nginx-0.7.68/html/object/Pepole.php";
class Man extends People {
private $sex;
function __construct() {
parent::__construct();
$this->sex = "M";
}
public function getSex() {
return $this->sex;
}
}
?>

说明:

  • 在Man的构造方法中调用父类的构造方法,增加的代码是:parent::__construct();

三、总结 | Summary

当子类有自定义的构造方法时,应在子类的自定义构造方法中调用父类的构造方法。如果在父类的构造方法中有初始化一些成员的数据,不调用父类的构造方法会导致子类对象的数据不完整。

这一点熟悉Java的童鞋们可能会觉得有点郁闷:PHP为什么不会自动调用父类的默认构造方法来初始化父类实例呢