例子:
class Student {
public $name;
public function __construct($value) { //構造函數,好處是賦值類的同時也是賦值函數;
$this->name=$value;
}
}
class sch {
public $s
function __construct(
$this->s = $s
}
}
$doo = new sch(new Student('20')); // $value賦值20,$name的值也變為20,同時也是為sch實例對象賦值
print_r($doo);
輸出結果:
sch Object ( [s] => Student Object ( [name] => 20 ) )
當然上述的#1,#2,#3也可以改為以下代碼:
public $snum;
function __construct(Student $s) {
$this->snum = $s;
整個輸出結果:
sch Object ( [snum] => Student Object ( [name] => 20 ) )
如果包含子類,也可通過子類實例化,如下例:
class same { //父類;
private $one = 11;
public function __construct() {
return $this->one;
}
}
class Example extends same { //子類; 繼承父類。
private $two = 22;
public function showTwo() {
return "hello ".$this->two;
}
}
class showStr {
public function getStr(same $me) { //參數為父類same;
echo $me->showTwo();
}
}
showStr::getStr(new Example); //實例化子類作參
輸出為:hello 22
如果最後一行改為父類作參,showStr::getStr(new same); 則會提示:Fatal error: Call to undefined method same::showTwo() ,即在父類same沒能找到showTwo()方法。這時可以用類比較符instanceof來判斷,以免選錯類。
class showStr {
public function getStr(same $me) {
if ($me instanceof Example) {
echo $me->showTwo();
} else {
echo "對不起,選錯類啦!";
}
}
}
showStr::getStr(new same);
輸出:對不起,選錯類啦!