Introduction to the usage of $this in php

王林
Release: 2023-04-08 14:50:01
Original
3055 people have browsed it

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

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

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!

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!