Home >Backend Development >PHP Tutorial >Introduction to the usage of $this in php

Introduction to the usage of $this in php

王林
王林Original
2020-04-25 11:14:333139browse

Introduction to the usage of $this in php

In php, we usually declare a class first, and then use this class to instantiate objects!

Usage:

$this means the specific object after instantiation.

$this->Indicates using the attributes or methods of this class within the class itself.

The ‘->’ symbol is the “infix dereference operator”. In other words, it is a method that calls a subroutine whose parameters are passed by reference (among other things, of course). As we mentioned above, when calling PHP functions, most parameters are passed by reference.

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.

<?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 $user1->getName() is called, the code in the User class above echo $this->name ; is equivalent to echo $user1->name;

For more related tutorials, please pay attention to php中文网.

The above is the detailed content of Introduction to the usage of $this 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