php logo on purple background

PHP: when to use ‘self’ and when to use ‘$this’?

By

in

In PHP, the term $this is utilized to point to the current instance of the class whereas the term self is used to indicate the class itself.

Its recommended to use $this when referring to instance level properties or methods within the class, like accessing a property of the object or invoking a method of the present object.

For example:

class MyClass {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function sayHello() {
        echo "Hello, my name is " . $this->name;
    }
}

$obj = new MyClass("John");
$obj->sayHello(); // output: "Hello, my name is John"

On the other hand, you should use self when referring to static properties or methods within the same class, such as when accessing a static property or calling a static method of the class.

For example:

class MyClass {
    private static $count = 0;

    public function __construct() {
        self::$count++;
    }

    public static function getCount() {
        return self::$count;
    }
}

$obj1 = new MyClass();
$obj2 = new MyClass();
echo MyClass::getCount(); // output: 2

In summary, $this is used for instance-level properties and methods, while self is used for static properties and methods.



Comments

Leave a Reply

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