Home > Backend Development > PHP Problem > Understanding and examples of $this in PHP

Understanding and examples of $this in PHP

王林
Release: 2023-02-23 09:58:02
Original
2707 people have browsed it

When we write php scripts, we often use $this, so how do we understand $this?

Next, I will demonstrate the use of $this:

First of all, we usually create a class when writing a script, so we first create a class User

class User
{
public $name;
}
Copy after login

Next, we write another method getName(). The function of this method is to output the attribute $name

class User
{
public $name;
public function getName() {
echo $this->name;
}
}
//使用
$user1 = new User();
$user1->name = 'liming';
$user1->getName();//会输出'liming'
$user2 = new User();
$user2->name = 'zhagsan';
$user2->getName();//输出'zhangsan'
Copy after login

How to understand?

The above example creates two objects. When $user1->getName, at this time, $this represents $user1.

The above is my understanding, I hope it will be helpful to everyone. Thanks!

For more PHP related questions, you can visit the PHP Chinese website: https://www.php.cn/

Recommended PHP related video tutorials: https ://www.php.cn/course/list/29/type/2.html

The above is the detailed content of Understanding and examples of $this in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Latest Issues
Why is this ID written like this?
From 1970-01-01 08:00:00
0
0
0
Small question about $this
From 1970-01-01 08:00:00
0
0
0
This file demo.mp4
From 1970-01-01 08:00:00
0
0
0
What's the use of this?
From 1970-01-01 08:00:00
0
0
0
javascript - es6中this
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template