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
PHP OOP Introduction
PHP Class
PHP Objects
Exercises & Assignments
No Content Found.
Interview Questions & Answers
How to create a class and object in PHP?
What is the difference between public, private and protected in PHP?
Is multiple inheritance supported in PHP?
What is the meaning of final class and final method in PHP?
What is the difference between abstract class and interface in PHP?
What are traits in PHP?
What is a constructor in PHP?