php中this关键字用法分析

2017-03-01 11:01:38 php
这篇文章主要介绍了php中this关键字用法,结合具体实例分析了this关键字访问类内部变量与方法的原理与相关使用技巧,需要的朋友可以参考下

本文实例讲述了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”。