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

These three keywords are used inside a class, but they point to different things.

KeywordWhat it meansUsed for
$thisThe current objectNormal properties and methods
selfThe class where the code is writtenStatic properties, constants and static methods
staticThe class that was actually called (late static binding)Static methods when child classes are involved
<?php
class Car {
    public $name = "Swift";
    public static $wheels = 4;

    public function show() {
        return $this->name . " has " . self::$wheels . " wheels";
    }
}

$car = new Car();
echo $car->show();
?>

Output:

Tutorials Class - Output Window

Swift has 4 wheels

The difference between self and static is seen when a child class calls the method.

<?php
class A {
    public static function create() {
        return new static();   // self would always create class A
    }
}

class B extends A {}

echo get_class(B::create());
?>

Output:

Tutorials Class - Output Window

B

If we had written new self(), the output would be A.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.