Sobes.tech
Junior

What is the difference between the keywords 'self' and 'this' in PHP?

sobes.tech AI

Answer from AI

$this refers to the current instance of the object. self refers to the current class (in a static context or within methods to access static members).

$this:

  • Used to access properties and methods of a specific class instance.
  • Applied within non-static methods.
class MyClass {
    public $instanceProperty = 'Hello';

    public function getInstanceProperty() {
        // Access to the current instance property
        return $this->instanceProperty;
    }
}

self:

  • Used to access static properties and methods of the class.
  • Applied within static and non-static methods.
class MyClass {
    public static $staticProperty = 'World';

    public static function getStaticProperty() {
        // Access to the static property
        return self::$staticProperty;
    }

    public function accessStaticFromInstance() {
        // Access to static property from a non-static method
        return self::$staticProperty;
    }
}

Example of using $this and self together:

class Example {
    public $instanceId;
    private static $count = 0;

    public function __construct() {
        // Using self to increment static counter
        self::$count++;
        // Using $this to set instance property
        $this->instanceId = self::$count;
    }

    public static function getCount() {
        // Using self to get static property
        return self::$count;
    }

    public function getInstanceId() {
        // Using $this to get instance property
        return $this->instanceId;
    }
}
What is the difference between the keywords 'self'… - sobes.tech