PHP建構函式詳解

來源:互聯網
上載者:User

這篇文章介紹的內容是關於 PHP建構函式詳解 ,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

// ===代碼部分1===

class Human {    public $name = '李四';        public $gender = '男';}$a = new Human();$b = new Human();$c = new Human();echo $a->name,'<br >';echo $b->name,'<br >';echo $c->name,'<br >';// 三個李四echo $a->gender,'<br >';echo $b->gender,'<br >';echo $c->gender,'<br >';// 三個男echo '<hr >';



// ===筆記部分1===

/*
在類裡,有一個建構函式,
用來初始化對象用的,
利用建構函式,你有機會操作對象,
來改變它的值

建構函式 __construct();
建構函式的使用時機:
每當new一個對象,就會自動新new出來的對象發揮作用
*/



// 建構函式__construct()

// ===代碼部分2===

class People {    public function __construct() {        $this->name = '李四';        $this->gender = '女';    }    public $name = null;    public $gender = null;}$a = new People();$b = new People();$c = new People();echo $a->name,'<br >';echo $b->name,'<br >';echo $c->name,'<br >';// 三個李四echo '<hr >';



// ===代碼部分3===

class People2 {    public function __construct($name,$gender) {// 通過在建構函式括弧內定義變數,傳給構造方法        $this->name = $name;        $this->gender = $gender;    }// 建構函式無法重載    /*    public function __construct() {        $this->name = 'nobody';    }    */    public $name = null;        public $gender = null;}$a = new People2('張飛','男');$b = new People2('空姐','女');$c = new People2('孫二娘','女');echo $a->name,'<br >';echo $b->name,'<br >';echo $c->name,'<br >';echo '<hr >';



// 解構函式__destruct()

// ===筆記部分2===

/*
解構函式 __destruct();

建構函式是在對象產生的時候,自動執行
解構函式是在對象銷毀的時候,自動執行

建構函式就是出生時啼哭
解構函式就是臨終遺言

對象如何銷毀?
1、顯式的銷毀,unset,賦值為null,都可以
2、PHP在代碼執行到最後一行時,所有申請的記憶體都要釋放掉
自然,對象的那段記憶體也要釋放,對象就被銷毀了.

*/



// ===代碼部分4===

class Human2 {    public $name = null;        public $gender = null;        public function __construct() {        echo '出生了<br >';    }        public function __destruct() {        echo '再見<br >';    }}$a = new Human2();$b = new Human2();$c = new Human2();$d = new Human2();unset($a);$b = false;$c = null;echo '<hr >';

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.