King Loves Coding PHP What is the difference between using self and $this in PHP?

What is the difference between using self and $this in PHP?

0 Comments

Difference Between Using self and $this in PHP

In PHP, self and $this are both used within classes but serve different purposes:

  • $this refers to the current object instance. It’s used to access non-static members (properties or methods) of the object.
  • self refers to the current class. It’s primarily used to access static members (properties or methods) of the class.

Correct Usage Example

class X {
    private $non_static_member = 1;
    private static $static_member = 2;
 
    function __construct() {
        echo $this->non_static_member . ' '
           . self::$static_member;
    }
}
 
new X();

Incorrect Usage Example:

class X {
    private $non_static_member = 1;
    private static $static_member = 2;
 
    function __construct() {
        echo self::$non_static_member . ' '
           . $this->static_member;
    }
}
 
new X();

Polymorphism with $this:

class X {
    function foo() {
        echo 'X::foo()';
    }
 
    function bar() {
        $this->foo();
    }
}
 
class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}
 
$x = new Y();
$x->bar();

Polymorphism with self:

class X {
    function foo() {
        echo 'X::foo()';
    }
 
    function bar() {
        self::foo();
    }
}
 
class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}
 
$x = new Y();
$x->bar();

Conclusion

Using $this->foo() invokes polymorphic behavior, calling the foo() method of the exact type of the current object. On the other hand, self::foo() suppresses polymorphism, always invoking the foo() method defined in the current class.

Leave a Reply

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