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

Understanding and examples of $this in PHP

王林
王林Original
2019-08-19 14:11:102657browse

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

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'

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!

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