Current Location: Home> Latest Articles> Difference Between self and this in PHP and How to Use Them

Difference Between self and this in PHP and How to Use Them

gitbox 2025-08-02

Difference Between self and this in PHP

In PHP, both self and this are used to access class properties and methods, but they serve different purposes and have distinct meanings.

Definition and Usage of self

self is a special identifier that refers to the current class itself and is mainly used to access static properties and static methods. It's worth noting that self is case-insensitive in PHP, so Self, SELF, or self all work.

Definition and Usage of this

this is a variable pointing to the current object instance, primarily used to access non-static properties and non-static methods. It can only be effectively used inside class methods.

Example of Using self

The following example defines a class named Foo with a static property and a static method to demonstrate how to use self to access static members:

class Foo {
    public static $staticProperty = "This is a static property.";
    public static function staticMethod() {
        echo self::$staticProperty;
    }
}
Foo::staticMethod();

This code outputs:

This is a static property.

Example of Using this

Continuing with the Foo class, this time adding a non-static property and method to show how to use this to access object members:

class Foo {
    public $nonStaticProperty = "This is a non-static property.";
    public function nonStaticMethod() {
        echo $this->nonStaticProperty;
    }
}
$foo = new Foo();
$foo->nonStaticMethod();

The output is:

This is a non-static property.

Summary of self and this

In PHP object-oriented programming, self is mainly used to access static members of the current class, while this refers to the current object instance to access non-static members. Specifically:

  • self: Used inside the class to call static properties and methods; case-insensitive.
  • this: Used inside class methods, refers to the current object's properties and methods.

Understanding and properly using self and this helps write clear and maintainable PHP code.

Hope this article helps you grasp the difference and usage of self and this in PHP.