PHP物件導向____PHP

來源:互聯網
上載者:User

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



聯繫我們

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