類是變數與作用於這些變數的函式的集合。使用下面的語法定義一個類:
<?php
class Cart
{
var $items; // Items in our shopping cart
// Add $num articles of $artnr to the cart
function add_item ($artnr, $num)
{
$this->items[$artnr] += $num;
}
// Take $num articles of $artnr out of the cart
function remove_item ($artnr, $num)
{
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} else {
return false;
}
}
}
?> |
上面的例子定義了一個 Cart 類,這個類由購物車中的商品構成的陣列和兩個用於 從購物車中增加和刪除商品的函陣列成。
| 注意 |
下面的警告注解對 PHP4 有效。 名稱 stdClass 已經被 Zend 使用並保留。您不能在您的 PHP 代碼 中定義名為 stdClass 的類。 The function names __sleep and __wakeup are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them. See below for more information. PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality. |
註: 在 PHP 4 中,var 變數的值只能初始化為常數。用非常數值初始化變數, 您需要一個初始化函式,該函式在對象被創建時自動被呼叫。這樣一個函式被稱之為建構函式 (見下面)。
<?php /* None of these will work in PHP 4. */ class Cart { var $todays_date = date("Y-m-d"); var $name = $firstname; var $owner = 'Fred ' . 'Jones'; var $items = array("VCR", "TV"); } /* This is how it should be done. */ class Cart { var $todays_date; var $name; var $owner; var $items; function Cart() { $this->todays_date = date("Y-m-d"); $this->name = $GLOBALS['firstname']; /* etc. . . */ } } ?>
Classes are types, that is, they are blueprints for actual variables. You have to create a variable of the desired type with the new operator.
<?php
$cart = new Cart;
$cart->add_item("10", 1);
$another_cart = new Cart;
$another_cart->add_item("0815", 3); |
上述代碼創建了兩個 Cart 類的對象 $cart 和 $another_cart, 對象 $cart 的方法 add_item() 被呼叫時,增加了1件10號商品。對於對象 $another_cart, 3件0815號商品被增加到購物車中。
$cart 和 $another_cart 都有方法 add_item(), remove_item() 和一個 items 變數。 它們都是明顯的函式和變數。你可以把它們當作文件系統中的某些類似目錄的東西來考慮。 在文件系統中,你可以擁有兩個不同的 README.TXT 文件,只要不在相同的目錄中。 正如從為了根目錄連接每個文件你需要輸入該文件的完整的路徑名一樣,你必須指定需 要呼叫的函式的完整名稱:在 PHP 術語中,根目錄將是全域名稱空間,路徑名符號將是 ->。因而,名稱 $cart->items 和 $another_cart->items 命名了兩個不同的 變數。注意變數 $cart->items,不是 $cart->$items,那是因為在 PHP 中一個變數 名只有一個單獨的美元符號。
// correct, single $
$cart->items = array("10" => 1);
// invalid, because $cart->$items becomes $cart->""
$cart->$items = array("10" => 1);
// correct, but may or may not be what was intended:
// $cart->$myvar becomes $cart->items
$myvar = 'items';
$cart->$myvar = array("10" => 1); |
在一個類的定義內部,你無法得知使用何種名稱的對象是可以連接的:在編寫 Cart 類時,並 不知道之後對象的名稱將會命名為 $cart 或者 $another_cart。因而你不能在類中使用 $cart->items。然而為了類定義的內部連接自身的函式和變數, 可以使用偽變數 $this 來達到這個目的。$this 變數可以理解為‘我自己的’或者‘當前對象’。因而 ‘$this->>items[$artnr] += $num’ 可以理解為‘我自己的物品陣列的 $artnr 計數器加 $num’ 或者 ‘在當前對象的物品陣列的 $artnr 計數器加 $num’。
註: 有一些不錯的函式用來處理類和對象。你應該關注一下 類/對象 函式。