PASSWORD RESET

Your destination for complete Tech news

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

394 0
< 1 min read

In PHP, self is a keyword that refers to the current class, while $this is a reference to the current object.

self is used to access static properties, constants, and methods of the current class, while $this is used to access non-static properties and methods of the current object.

For example:

class MyClass {
  const MY_CONST = 'Hello';
  static $myStaticProp = 'World';

  public function myMethod() {
    echo self::MY_CONST; // Outputs 'Hello'
    echo self::$myStaticProp; // Outputs 'World'
  }
}

$obj = new MyClass();
echo $obj->myMethod(); // Outputs 'HelloWorld'

In the above example, self is used to access the static property $myStaticProp and the constant MY_CONST of the MyClass class.

On the other hand, $this is used to access the properties and methods of an object. For example:

class MyClass {
  public $myProp = 'Hello';

  public function myMethod() {
    echo $this->myProp; // Outputs 'Hello'
  }
}

$obj = new MyClass();
echo $obj->myMethod(); // Outputs 'Hello'

In the above example, $this is used to access the property $myProp of the $obj object.

It is important to note that self can only be used inside a class, while $this can only be used inside an object.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.