PHP supports classes and other object-oriented constructs. Static functions and variables in PHP classes are not associated with any specific instance of the class (in other words, an object). See difference between object and class.

Instead, static functions and variables are associated with the class definition itself. In other words, all instances of a class share the same static variable. Within the context of a method (function) of a class, static variables and functions are accessed using self::. Other methods and variables are used in the context of an object (an instance) of a class, using this->.

Comparison chart

self versus this comparison chart
Edit this comparison chartselfthis
Can be used in static functions Yes No
accessible class variable and methods with self:: $this-> (Note that PHP > 5.3 allows the use of $this with static variables use $this::$foo. $this->foo will still be undefined if $foo is a static var.)
Needs an instantiated object No Yes

self vs this in PHP - Examples

class exampleClass
    public static $foo;
    public $bar;
    public function regularFunction() { echo $this->bar; }

    public static function staticFunction() { echo self::$foo; }

    public static function anotherStatFn() { self::staticFunction(); }

    public function regularFnUsingStaticVar() { echo self::$foo; }
    // NOTE: As of PHP 5.3 using $this::$bar instead of self::$bar is allowed


exampleClass::$foo = "Hello";

$obj = new exampleClass();

$obj->bar = "World!";

exampleClass::staticFunction(); /* prints Hello */

$obj->regularFunction(); /* prints World! */

Static functions can only use static variables. Static functions and variables are referenced via self::functionName() or self::variableName. In the example shown above, static variables are referenced with the class name (exampleClass::$foo) or, with a self:: (self::$foo) when used within the static method [named staticFunction()] of the class.

Regular functions and variables of a class need an object context to be referenced. They cannot exist without an object context. The object context is provided by $this. In the above example, $bar is a regular variable and so it is referenced as $obj->bar (in the object context with variable obj) or as $this->bar (again in an object context within a method of an object).

self does not use a preceding $ because self does not connote a variable but the class construct itself. $this does reference a specific variable so it has a preceding $.


Share this comparison:

If you read this far, you should follow us:

"self vs. this in PHP." Diffen LLC, n.d. Web. 16 Oct 2016. < >