Detailed explanation of usage analysis of this keyword in php

墨辰丷
Release: 2023-03-28 11:38:02
Original
1574 people have browsed it

This article mainly introduces the usage of this keyword in PHP, and analyzes the principles and related usage techniques of this keyword to access internal variables and methods of classes based on specific examples. Friends in need can refer to this article

The example 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;
    }
  }
}
?>
Copy after login

Use a piece of code to illustrate the problem, in a class Inside the definition, you have no way of knowing under what name the object will be accessible: when you write the Cart class, you don't know whether the object will later be named $cart or $another_cart. Therefore you cannot use $cart->items in a class. However, in order to access its own functions and variables within a class definition, the pseudo variable $this can be used for this purpose. The $this variable can be understood as "my own" or "the current object". Therefore '$this->>items[$artnr] = $num' 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 entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

javascript thisDetailed explanation (graphic tutorial)

Examples to explain the this pointing error solution in JavaScript (picture and text tutorial)

this# in JavaScript ##Detailed answers (graphic tutorial)

The above is the detailed content of Detailed explanation of usage analysis of this keyword in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!