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