In PHP OOP, self and $this are both used inside a class, but they work in very different ways:
1. $this
- Refers to the current object instance of the class.
- Can only be used inside non-static methods.
- Used to access instance properties and instance methods.
Example:
class Test {
public $name = "Himanshu";
public function showName() {
echo $this->name; // Refers to the object's $name
}
}
$obj = new Test();
$obj->showName(); // Output: Himanshu
Here, $this means “the current object $obj“.
2. self
- Refers to the current class itself, not an object.
- Can be used in static and non-static methods.
- Used to access static properties and static methods.
- Does not work with object context — it’s bound to the class where it is written.
Example:
class Test {
public static $name = "PHP";
public static function showName() {
echo self::$name; // Refers to the class's static property
}
}
Test::showName(); // Output: PHP
Here, self means “this class (Test)”.
Main Differences Table
| Feature | $this | self |
|---|---|---|
| Refers to | Current object instance | Current class |
| Static context usage | ❌ No | ✅ Yes |
| Instance context usage | ✅ Yes | ✅ Yes (but not for instance members) |
| Accesses | Instance properties/methods | Static properties/methods |
| Bound to | Object at runtime | Class at compile time |
💡 Quick way to remember:
$this→ “this object”self→ “this class”
