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

What is the function of this keyword in php

王林
王林Original
2020-06-30 09:23:394459browse

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;
}
?>

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();       //这里会输出李四!
?>

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!

Statement:
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