Home > Backend Development > PHP Problem > What is the function of this keyword in php

What is the function of this keyword in php

王林
Release: 2023-03-01 18:08:02
Original
4473 people have browsed it

The function of this keyword in php is to determine who to point to when instantiating. this is a pointer to the current object instance, it does not point to any other object or class. The usage of this keyword is [$this->], which means using the attributes or methods of this class within the class itself.

What is the function of this keyword in php

Function:

This is used to determine who it points to when instantiating. Therefore, this is a pointer to the current object instance and does not point to any other object or class.

Specific analysis:

$this means the specific object after instantiation! $this-> means using the attributes or methods of this class within the class itself. The ‘->’ symbol is the “infix dereference operator”.

Example:

For example, we declare a User class! It only contains one attribute $name;

<?php
class User
{
   public $_name;
}
?>
Copy after login

Now, we add a method to the User class. Just use the getName() method to output the value of the $name attribute!

<?php
class User
{
      public $name;
      function getName()
      {
             echo $this->name;
      }
}
$user1 = new User();
$user1->name = &#39;张三&#39;;
$user1->getName();        //这里就会输出张三!
$user2 = new User();
$user2->name = &#39;李四&#39;;  
$user2->getName();       //这里会输出李四!
?>
Copy after login

Two User objects are created above. They are $user1 and $user2 respectively.

When calling $user1->getName(). The code in the User class above echo $this->name; is equivalent to echo $user1->name;

If you want to know more related tutorials, please visit php中文网.

The above is the detailed content of What is the function 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