第二次實(shí)例化對(duì)象的時(shí)候,不執(zhí)行
<?php
date_default_timezone_set("PRC");
//類(lèi)的定義以關(guān)鍵字class開(kāi)始,后面跟著這個(gè)類(lèi)的名稱(chēng)。類(lèi)的命名通常每個(gè)單詞的第一個(gè)字母大寫(xiě)。以中括號(hào)開(kāi)始和結(jié)束
class Nbaplayer
{
? ? public $name = "Jordan";
? ? public $height = "198cm";
? ? public $weight = "98kg";
? ? public $team = "Bull";
? ? public $playerNum = "23";
? ??
? ? //構(gòu)造函數(shù),在對(duì)象被實(shí)例化的時(shí)候自動(dòng)調(diào)用
? ? function __construct($name,$height,$weight,$team,$playerNum)
? ? {
? ? ? ? echo "In Nbaplayer constructor"."\n";
? ? ? ? $this->name =$name;
? ? ? ? //$this是PHP里面的偽變量,表示對(duì)象自身??梢酝ㄟ^(guò)$this->的方式訪問(wèn)對(duì)象的屬性和方法
? ? ? ? $this->height =$height;
? ? ? ? $this->weight =$weight;
? ? ? ? $this->team = $team;
? ? ? ? $this->playerNum =$playerNum;
? ? }
? ? //定義方法
? ? public function run()
? ? {
? ? ? ? echo "Running\n";
? ? }
? ? public function jump()
? ? {
? ? ? ? echo "Jumping\n";
? ? }
? ? public function dribble()
? ? {
? ? ? ? echo "Dibbling\n";
? ? }
? ? public function shoot()
? ? {
? ? ? ? echo "Shooting\n";
? ? }
? ? public function dunk()
? ? {
? ? ? ? echo "Dunking\n";
? ? }
? ? public function pass()
? ? {
? ? ? ? echo "Passing\n";
? ? }
}
//類(lèi)到對(duì)象的實(shí)例化
//類(lèi)的實(shí)例化為對(duì)象是使用關(guān)鍵字new,new之后緊跟類(lèi)的名稱(chēng)和一對(duì)括號(hào)
$Jordan = new Nbaplayer("Jordan","198cm","98kg","Bull","23");
//對(duì)象中的屬性成員可以通過(guò)->符號(hào)來(lái)訪問(wèn)
echo $Jordan -> name."\n";
$Jordan -> dribble()."\n";
$Jordan -> pass()."\n";
//每一次用new實(shí)例化對(duì)象的時(shí)候,都會(huì)用類(lèi)名后面的參數(shù)列表調(diào)用構(gòu)造函數(shù)
$Jordan = new Nbaplayer("James","203cm","120kg","Heat","6");
echo $James->name."\n";
?>
執(zhí)行結(jié)果:
In Nbaplayer constructor | |
Jordan | |
Dibbling | |
Passing | |
In Nbaplayer constructor | |
2021-01-14
最后一個(gè)實(shí)例化的對(duì)象沒(méi)寫(xiě)對(duì),問(wèn)題發(fā)現(xiàn)了
2021-01-14
最后一個(gè)echo