Home >Backend Development >PHP Tutorial >Analysis of usage of this keyword in php
The example in this article describes the usage of this keyword in php. Share it with everyone for your reference, the details are as follows:
The following defines a Cart class
<?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; } } } ?>
Using a piece of code to illustrate the problem, within the definition of a class, you cannot know what name the object is accessible to : When writing the Cart class, I didn’t know that the object would be named $cart later. Or $another_cart. Therefore you cannot use $cart->items in a class. However, in order to access its own functions and variables from within a class definition, you can use the pseudo variable $this to achieve this purpose. The $this variable can be understood as "my own" or "the current object". Thus '$this->>items[$artnr] += $num' It can be understood as "add $num to the $artnr counter of my own item array" or "add $num to the $artnr counter of the current object's item array".
The above is the analysis of the usage of this keyword in php. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!