首页 > 语言 > PHP > 正文

php中this关键字用法分析

2024-05-04 23:53:23
字体:
来源:转载
供稿:网友

本文实例讲述了php中this关键字用法。分享给大家供大家参考,具体如下:

下面定义了一个Cart类

<?phpclass 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”。

 

希望本文所述对大家PHP程序设计有所帮助。


注:相关教程知识阅读请移步到PHP教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选