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 = '张三'; $user1->getName(); //这里就会输出张三! $user2 = new User(); $user2->name = '李四'; $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!