HomeCoding & Programming

Difference between $this and self in PHP

Like Tweet Pin it Share Share Email

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

 

PHP classes can have static functions and static variables.Declaring class methods or properties as static make them accessible without needing an instance of the class or an object.

 

Static functions and variables in classes are not associated with any object, but associated with the class definition itself.
You can say all instances of a class share the same static variable and functions.

 

Inside a class definition, $this refers to the current object, while self(not $self) refers to the current class.
self does not use a preceding $ because self does n’t represent a variable but the class construct itself.$this does reference a specific variable so it has a $ prefix.

 

It is necessary to refer to a class element using self & refer to an object element using $this, use $this->var for non-static variables, use self::$var for static variables and same for methods.

 


class demoClass
{
	public $var;
	public static $svar;
	
	public function regular_function()
	{ echo $this->var; }
	
	public static function static_function()
	{ echo self::$svar; }
	
	public static function another_static_fn()
	{ self::static_function(); }
	
	public function regular_fn_using_static_var()
	{ echo self::$svar; }
}

demoClass::$svar = "Script";

$obj = new demoClass();
$obj->var = "Article";

echo demoClass::static_function();
echo $obj->regular_function();

 

Note:

  • static functions can only use static variables. The way static functions and static variables are referenced is self::functionName() or self::variableName.
  • Regular functions and variables of a class need an object to be referenced.