Reference — What does this symbol mean in PHP?
In PHP, $this
is a special variable that refers to the current object. It can be used inside any object method when you want to access the current object's properties or methods.
For example, let's say you have a class called User
with a property called name
and a method called getName
. You could use $this
to access the name
property and return it from the getName
method like this:
<?php
class User
{
public $name;
public function getName()
{
return $this->name;
}
}
Watch a video course
Learn object oriented PHP
You can then create an instance of the User
class and use the getName
method to retrieve the value of the name
property:
<?php
class User
{
public $name;
public function getName()
{
return $this->name;
}
}
$user = new User();
$user->name = 'John';
echo $user->getName(); // Outputs 'John'
Note that $this
can only be used inside object methods, and it cannot be used in functions or class constants.