php構造方法與析構方法

來源:互聯網
上載者:User

標籤:person   構造方法   color   執行個體化   程式   對象   列表   執行個體   blog   

1. 構造方法<?php//構造方法 __construct() 是在執行個體化對象時被自動調用//用途:可以用於初始化程式(可以給成員屬性賦值,也可以調用成員方法)//文法:[修飾符] function __construct(參數列表...){ }// 構造方法方法格式:// [修飾符] function __construct([參數]){//     程式體// }class person{    public $name;    public $age;    public $sex;    public function __construct($n, $a, $s){        $this -> name = $n;        $this -> age = $a;        $this -> sex = $s;    }    public function say(){        echo "我的名字是:{$this -> name},我的年齡是:{$this -> age},我的性別是:{$this -> sex}";    }}//執行個體化對象時要按構造方法的參數去傳遞對應的值$person1 = new person("張三", 18, "男");echo $person1 -> name;echo "<br />";echo $person1 -> age;echo "<br />";echo $person1 -> sex;echo "<br />";$person1 -> say();?>2. 析構方法<?php//析構方法,是對象在銷毀時自動調用的//指令碼執行完之後,才會銷毀對象class person{    public $name;    public $age;    public $sex;    public function __construct($name, $age, $sex){        $this -> name = $name;        $this -> age = $age;        $this -> sex = $sex;    }    public function say(){        echo "say";    }    /*    * 析構方法 __destruct() 是在對象被銷毀時自動調用    * 用途:可以進行資源釋放操作或檔案的關閉操作    * 注意:棧記憶體的先進後出    */    public function __destruct(){        echo "88{$this -> name}<br />";    }}$person = new person("zhangsan", 18, "nv");$person -> say();echo "<br />";$person1 = new person("lisi", 20, "nan");    //棧記憶體操作person1 -> say();?>

 

php構造方法與析構方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.