如何访问类变量和类函数
倘若你需要在类定义自身的内部访问它的函数或者变量,那么PHP 4和PHP 5均提供了$this关键字,该$this关键字用于指向“本“类。为了明白这个是如何工作的,让我们改变eat()方法以接受食物单元,然后将其加到熊的体重上。
<?php // PHP 5 // class definition class Bear { // define properties public $name; public $weight; // define methods public function eat($units) { echo $this->name." is eating ".$units." units of food... "; $this->weight += $units; } } ?>
在这个实例中,$this前缀指示待修改的变量存在于类的内部(或者,在英语中,“将提供给eat()函数的参数和对象内部的$weight变量相加”)。$this前缀因而提供了一种访问类内部变量和函数的便利方法。下面是关于它如何工作的例子:
<?php // create instance $baby = new Bear; $baby->name = "Baby Bear"; $baby->weight = 1000; // now create another instance // this one has independent values for each property $brother = new Bear; $brother->name = "Brother Bear"; $brother->weight = 1000; // retrieve properties echo $baby->name." weighs ".$baby->weight." units "; echo $brother->name." weighs ".$brother->weight." units "; // call eat() $baby->eat(100); $baby->eat(50); $brother->eat(11); // retrieve new values echo $baby->name." now weighs ".$baby->weight." units "; echo $brother->name." now weighs ".$brother->weight." units "; ?>
上述代码的输出就是:
Baby Bear weighs 1000 units Brother Bear weighs 1000 units Baby Bear is eating 100 units of food... Baby Bear is eating 50 units of food... Brother Bear is eating 11 units of food... Baby Bear now weighs 1150 units Brother Bear now weighs 1011 units