2014/02/23

PHP5 建構子與解建構子

PHP5之後新增Magic Methods,裡面有提到__construct以及__destruct()也是用來新增建構子解建構子

當你不在用到物件時,PHP會自動將物件釋放,釋放時會呼叫解建構子

<?php
 header("Content-Type:text/html; charset=utf-8");
 
 class MyTest{
  protected $str;
  const NAME = "CY";
  public static $number = 0;


  public function __construct($str){
   $this->$str = $str;
   echo "父" . $this->$str . "<br>";
  }

  public function __destruct(){
   echo "解建構<br>";
  }

  public function SetNumber($number){
   self::$number = $number;
  }

  public function GetNumber(){
   return self::$number;
  }
 }


 class MyTest2 extends MyTest{
  public function __construct($str){
   parent::__construct($str);
   $this->$str = $str;
   echo "子" . $this->$str . "<br>";
  }

  public function __destruct(){
   echo "解建構<br>";
  }

  public function SetNumber($number1, $number2){
   parent::SetNumber($number1+$number2);
  }

  public function GetNumber(){
   return self::$number;
  }

 }

 $test = new MyTest("建構子");
 $test->SetNumber(5);
 echo "數字:" . $test->GetNumber() . "<br>";
 echo Mytest::NAME . "<br>";
 echo "--------------<br>";

 $test2 = new MyTest2("建構子");
 $test2->SetNumber(10, 20);
 echo "數字加總:" . $test2->GetNumber() . "<br>";

?>



參考資料:
http://www.php.net/manual/en/language.oop5.php
http://www.php.net/manual/en/language.oop5.decon.php
http://www.php.net/manual/en/language.oop5.visibility.php
http://www.php.net/manual/en/language.oop5.inheritance.php
http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php
http://www.php.net/manual/en/language.oop5.static.php