HomePHP OOPSWhat is the difference between self and $this?

What is the difference between self and $this?

self and $this

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$thisself
Refers toCurrent object instanceCurrent class
Static context usage❌ No✅ Yes
Instance context usage✅ Yes✅ Yes (but not for instance members)
AccessesInstance properties/methodsStatic properties/methods
Bound toObject at runtimeClass at compile time

💡 Quick way to remember:

  • $this → “this object”
  • self → “this class”

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *