PHP OOP - 類和物件
類是物件的模板,物件是類的例項。
OOP 案例
假設我們有一個名為 Fruit 的類。一個 Fruit 可以有 name、color、weight 等屬性。我們可以定義 $name、 $color 和 $weight 等變數來儲存這些屬性的值。
當建立單個物件(如 apple、banana 等)時,它們會繼承類的所有屬性和行為,但每個物件在屬性上會有不同的值。
定義一個類
類是透過使用 class
關鍵字定義的,後面跟著類名,然後是一對花括號({})。其所有屬性和方法都放在花括號內。
語法
<?php
class Fruit {
// 在此處編寫程式碼...
}
?>
下面我們宣告一個名為 Fruit 的類,它包含兩個屬性($name 和 $color)以及兩個方法 set_name() 和 get_name(),用於設定和獲取 $name 屬性。
<?php
class Fruit {
// 屬性
public $name;
public $color;
// 方法
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
注意:在類中,變數稱為屬性,函式稱為方法!
定義物件
沒有物件,類就毫無意義!我們可以從一個類建立多個物件。每個物件都擁有類中定義的所有屬性和方法,但它們會有不同的屬性值。
物件的建立使用 new
關鍵字。
在下面的示例中,$apple 和 $banana 是 Fruit 類的例項。
示例
<?php
class Fruit {
// 屬性
public $name;
public $color;
// 方法
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
自己動手試一試 »
在下面的示例中,我們向 Fruit 類添加了兩個方法,用於設定和獲取 $color 屬性。
示例
<?php
class Fruit {
// 屬性
public $name;
public $color;
// 方法
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit();
$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color();
?>
自己動手試一試 »
PHP - $this 關鍵字
$this 關鍵字指的是當前物件,並且只在方法內部可用。
看下面的例子
示例
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>
那麼,在哪裡可以更改 $name 屬性的值呢?有兩種方法:
1. 在類內部(透過新增 set_name() 方法並使用 $this)
示例
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
echo $apple->name;
?>
自己動手試一試 »
2. 在類外部(直接更改屬性值)
示例
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
echo $apple->name;
?>
自己動手試一試 »
PHP - instanceof
您可以使用 instanceof
關鍵字來檢查一個物件是否屬於某個特定類。