(3.21)PHP面向對象(一)
<?php
//類的關鍵字是class 通常第一個字母大寫,後加大括號
class NbaPlayer
{
//定義屬性
public $name="Jordan";
public $height="198cm";
public $weight="98kg";
public $team="Bull";
public $playNumber="23";
//構造函數在實例化時自動調用
function __construct($name,$height,$weight,$team,$playNumber)
{
echo "調用構造函數";
$this->name=$name; //$this 是php的偽變量,可以通過this—>訪問對象的方法和屬性
$this->height=$height;
$this->weight=$weight;
$this->team=$team;
$this->playNumber=$playNumber;
}
//析構函數 在執行結束時自動調用
function __destruct()
{
echo "destroying".$this->name."<br>";
}
//定義方法
public function run()
{
echo "running\n";
}
public function jump()
{
echo "jumping\n";
}
public function drible()
{
echo "dribbling\n";
}
public function shoot()
{
echo "shooting\n";
}
public function dunk()
{
echo "dunking\n";
}
public function pass()
{
echo "passing\n";
}
}
//對象的實例化 使用關鍵字new
$Jordan= new NbaPlayer("jordan","198cm","98kg","bull",23);
//對象中的成員變量和成員方法可以通過->來調用
echo $Jordan->name."<br>";
$Jordan->drible();
$Jordan->pass()."<br>";
//每次實例化對象 ,都會調用構造函數
$james=new NbaPlayer("james","203cm","120kg","heat",6);
$james->name;
?>