In PHP, $this
is a special variable that refers to the current instance of the class. It is used to access properties and methods of the current class within class methods.
Here is an example of how $this
is used in PHP:
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
$user = new User("John");
echo $user->getName(); // Outputs "John"
In this example, $this->name
refers to the $name
property of the current instance of the User
class. $this
is used in the getName()
method to access and return the value of the $name
property.
It’s important to note that $this
can only be used within class methods, and it cannot be used within static methods or outside of the class.