PHP對象是與java,c++幾點異同,
1.PHP 類可以複寫建構函式__construct和解構函式,這一點與c++相似,如果不寫則預設為無參構造和解構函式
<?phpclass NBAPlayer {}$jordan = new NBAPlayer();複寫構造和解構函式
<?phpclass NBAPlayer {public $name;public $height;public $weight;public $team;public $teamNumber;function __construct($name,$height,$weight,$team,$teamNumber){$this->name = $name;$this->height = $height;$this->weight = $weight;$this->team = $team;$this->teamNumber = $teamNumber;echo "construc a instance:".$name."<br/>";}function __destruct(){echo "Destroy a instance:".$this->name."<br/>";}}$jordan = new NBAPlayer("jordan","198cm","98kg","bull","23");$james = new NBAPlayer("james","205cm","120kg","heat","10");
2. $jordan 是一個對象的引用,並且php對象的記憶體釋放採用引用計數(與java類似),為0時候由gc自動調用析構。
&建立一個影子(別名)引用,並不增加引用計數。
<?phpclass NBAPlayer {public $name;public $height;public $weight;public $team;public $teamNumber;function __construct($name,$height,$weight,$team,$teamNumber){$this->name = $name;$this->height = $height;$this->weight = $weight;$this->team = $team;$this->teamNumber = $teamNumber;echo "construc a instance:".$name."<br/>";}function __destruct(){echo "Destroy a instance:".$this->name."<br/>";}}$jordan = new NBAPlayer("jordan","198cm","98kg","bull","23");$james = new NBAPlayer("james","205cm","120kg","heat","10");$james1 = $james;//相當於為james對象建立了一個新的引用$james2 = &$james1;//建立一個影子引用,其實是一個別名$james = null;echo "james1 has not yet set to be nulled <br/>";$james1 = null;//james對象調用析構(其引用計數已經為0)echo "james1 has set to be nulled<br/>";?>
運行結果:
construc a instance:jordanconstruc a instance:jamesjames1 has not yet set to be nulled Destroy a instance:jamesjames1 has set to be nulled Destroy a instance:jordan