定義基本類

PHP 中的物件包含變數和函式。物件通常屬於一個類,它定義了此類的所有物件將包含的變數和函式。

定義類的語法是:

class Shape {
    public $sides = 0;
    
    public function description() {
        return "A shape with $this->sides sides.";
    }
}

定義類後,你可以使用以下命令建立例項:

$myShape = new Shape();

物件的變數和函式可以這樣訪問:

$myShape = new Shape();
$myShape->sides = 6;

print $myShape->description(); // "A shape with 6 sides"

建構函式

類可以定義一個特殊的 __construct() 方法,該方法作為物件建立的一部分執行。這通常用於指定物件的初始值:

class Shape {
    public $sides = 0;
    
    public function __construct($sides) {
        $this->sides = $sides;
    }
    
    public function description() {
        return "A shape with $this->sides sides.";
    }
}

$myShape = new Shape(6);

print $myShape->description(); // A shape with 6 sides

擴充套件另一類

類定義可以擴充套件現有的類定義,新增新的變數和函式,以及修改父類中定義的那些。

這是一個擴充套件前一個示例的類:

class Square extends Shape {
    public $sideLength = 0;
    
    public function __construct($sideLength) {
       parent::__construct(4);
       
       $this->sideLength = $sideLength;
    }
    
    public function perimeter() {
        return $this->sides * $this->sideLength;
    }

    public function area() {
        return $this->sideLength * $this->sideLength;
    }
}

Square 類包含 Shape 類和 Square 類的變數和行為:

$mySquare = new Square(10);

print $mySquare->description()/ // A shape with 4 sides

print $mySquare->perimeter() // 40

print $mySquare->area() // 100