PHP面向對象

PHP對象是與java,c++幾點異同,

1.PHP 類可以複寫構造函數__construct和析構函數,這一點與c++相似,如果不寫則默認爲無參構造和析構函數

<?php
class NBAPlayer {
}
$jordan = new NBAPlayer();
複寫構造和析構函數

<?php
class 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自動調用析構。

&創建一個影子(別名)引用,並不增加引用計數。

<?php
class 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:jordan
construc a instance:james
james1 has not yet set to be nulled 
Destroy a instance:james
james1 has set to be nulled 
Destroy a instance:jordan



發佈了41 篇原創文章 · 獲贊 6 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章