建構子

是在使用類別建立實體時,會被自動呼叫的一個特殊函式。換個方式說,就有點像是程式的初始化。

他的公式:

class HelloOOP{

    //建構子 For PHP5
    function __construct(){

    }

    //建構子 For PHP4

    function HelloOOP(){

    } 

}

$A=new HelloOOP();

她的關鍵字 __construct(),這是在PHP5以後的版本才有支援。但是在PHP 4 建構子的寫法是"與類別同名稱相同的函式",再PHP 5這種方法仍然保留有這種寫法。但是當你在類別裡面同時存在__construct()跟"與類別同名稱相同的函式",那他會以__construct函式為優先。

但是如果你再宣告的時候,想傳入引數,那該怎麼做呢?我這邊以PHP 5來做為範例。

class HelloOOP{

         var $memberA;
         var $memberB;

         //建構子 For PHP5
         function __construct($inputA,$inputB){
             $this->memberA=$inputA;
             $this->memberB=$inputB;
         }

}

$A=new HelloOOP("HELLO","你好");

這個宣告會把"HELLO"跟"你好" 傳入,並指派給成員變數 $memberA跟$memberB。

解建構子

解建構子再類別裡面是在物件被釋放時,會自動被呼叫的特殊函數。但是在PHP4以前的版本裡面是沒有解建構子的方法。

class HelloOOP{

var $memberA;
var $memberB;

//建構子 For PHP5
function __construct($inputA,$inputB){
$this->memberA=$inputA;
$this->memberB=$inputB;
}

//定義解建構子
function __destruct(){

    echo "這個類別被解開了!";

     }

}

$A=new HelloOOP("HELLO","你好");

上面紅色的那段就是解建構子的方法。

arrow
arrow
    全站熱搜

    阿基 發表在 痞客邦 留言(0) 人氣()