PHP第二天!!黑人继续蒙蔽 什么是构造函数&析构函数

构造函数

 

  构造函数:constructor,php构造函数是类中的一个特殊函数,当使用 new 操作符创建一个类的实例时,构造函数将会自动调用。两根下化线开头的被称为魔术函数。

  作用:为对象成员变量赋初始值。

  注意:如果子类中定义了构造函数则不会暗中调用其父类的构造函数。要执行父类的构造函数,需要在子类的构造函数中调用 parent::__construct()。

  代码如下:

/*定义人类,男女区别
* 定义一个PERSON
* 添加名字,性别
*/
//class Person
//{
// public $name;
// public $gender;
//
// //定义一个函数为身体
// public function body()
// {
// echo "the body have different that woman and male";
// }
//
// //desc装入个别的信息,如姓名,性别
// public function desc()
// {
// echo'男女区别:<br>';
// }
// //设置一个构造函数传入姓名性别
// public function __construct($name, $gender)
// {
// $this->name = $name;
// $this->gender = $gender;
// }
//}
//
////定义人种
//class Woman extends Person
//{
//// public function __construct($name){
//// $this -> name = $name;
//// }
// //身体描述
// public function body()
// {
// echo " the woman : have a big sister.<br>";
// echo " the woman : not have little brother.<br>";
//
// }
//
// public function desc()
// {
// //当前类的父类对象,使用可以调用被覆盖的父类的属性和行为
// parent::desc();
// echo 'the woman name : ' . $this->name;
// echo "<br>Gender : " . $this->gender;
// $this->body();
// }
//}
//
////定义人种
//class Male extends Person
//{
//// public function __construct($name){
//// $this -> name = $name;
//// }
// //身体描述
// public function body()
// {
// echo "the male : have a big brother.<br>";
// echo "the male : not have big sister.<br>";
//
// }
//
// public function desc()
// {
// echo 'the male name : ' . $this->name;
// echo "<br>Gender : " . $this->gender;
// $this->body();
// }
//}
////定义人种
//class Me extends Person
//{
//// public function __construct($name){
//// $this -> name = $name;
//// }
// public function body()
// {
// echo "the male : have a big brother.<br>";
// echo "the male : not have big sister.<br>";
//
// }
// //身体描述
// public function desc()
// {
// echo 'the male name : ' . $this->name;
// echo "<br>Gender : " . $this->gender;
// $this->body();
// }
//}
//
//$animal = new Woman("夏娃", "女" . "<br>");
//$animal->desc();
//echo "<br><br>";
//$animal = new Male("亚当", "男" . "<br>");
//$animal->desc();
//echo "<br><br>";
//$animal = new Me("God", "男" . "<br>");
//$animal->desc();

析构函数

析构函数:__destructor,与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。析构函数往往用来做“清理善后” 的工作(例如在建立对象时用new开辟了一片内存空间,delete会自动调用析构函数后释放内存)。

目的:清理善后 的工作

注意:和构造函数一样,父类的析构函数不会被引擎暗中调用。要执行父类的析构函数,必须在子类的析构函数体中显式调用parent::__destruct()

 

posted @ 2017-07-16 01:55  电子E  阅读(127)  评论(0编辑  收藏  举报