php中this的含义

来源:百度知道 编辑:UC知道 时间:2024/04/30 11:59:34
详解php中$this->的含义

下面定义了一个Cart类
<?php
class Cart
{
var $items; // 购物车中的项目

// 把 $num 个 $artnr 放入车中

function add_item ($artnr, $num)
{
$this->items[$artnr] += $num;
}

// 把 $num 个 $artnr 从车中取出

function remove_item ($artnr, $num)
{
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} else {
return false;
}
}
}
?>
以一段代码说明问题,在一个类的定义内部,你无法得知使用何种名称的对象是可以访问的:在编写 Cart 类时,并不知道之后对象的名称将会命名为 $cart 或者 $another_cart。因而你不能在类中使用 $cart->items。然而为了类定义的内部访问自身的函数和变量,可以使用伪变量 $this 来达到这个目的。$this 变量可以理解为“我自己的”或者“当前对象”。因而 '$this->>items[$artnr] += $num' 可以理解为“我自己的物品数组的 $artnr 计数器加 $num”或者“在当前对象的物品数组的 $artnr 计数器加 $num”。