PHP的构造方法,析构方法和this关键字详细介绍 |
本文标签:构造方法,析构方法,this 一.什么是构造方法 { } { } 所以说一个类有且只有一个构造方法. 复制代码 代码如下: <?php header("Conter-Type:text/html;charset=utf-8"); class Person { public $name; //成员变量 public $age; // function __construct() //{ // echo "不带参数的构造方法"; //} function __construct($name,$age) { $this -> name = $name; $this -> age = $age; echo "带参数的构造方法"."<br />"; } //成员方法 function view() { //this的引用. echo "姓名:".$this ->name.", 年龄:".$this ->age; } } //new一个新的对象 //$p = new Person(); $p2 = new Person("李四",13); $p2 ->view(); ?> 结果如下: 复制代码 代码如下: <SPAN style="WIDOWS: 2; TEXT-TRANSFORM: none; TEXT-INDENT: 0px; FONT: 14px 微软雅黑; WHITE-SPACE: normal; ORPHANS: 2; LETTER-SPACING: normal; COLOR: #ff00ff; WORD-SPACING: 0px" color="#ff00ff"> 姓名:李四, 年龄:13</SPAN> 四:析构方法: 1.析构方法没有返回值. 2.主要作用是释放资源.并不是销毁对象本身. 4.一个类最多只有一个析构方法. 五:例子: 复制代码 代码如下: <?php header("Conter-Type:text/html;charset=utf-8"); class Person { public $name; public $age; //构造方法 function __construct($name,$age) { $this ->name = $name; $this ->age = $age; } //析构方法 function __destruct() { echo "姓名:".$this->name.", 年龄".$this->age."-->销毁<br />"; } } $p1= new Person("小一",18); $p2= new Person("小二",17); ?> 结果: 分析结论: 2.析构方法调用的顺序是先创建的对象后被销毁. 3.当一个对象没有引用,被垃圾回收机制确认为垃圾时,调用析构方法. |