Home >Backend Development >PHP Problem >Understanding and examples of $this in PHP
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!