When to use self and when to use $this in PHP? Understanding scope
Hello everyone! I started learning OOP in PHP and I constantly get confused about when to use `self` and when to use `$this`. Both seem to access class properties and methods, but there is clearly a difference, and I can't grasp it.
Here's a simple example that confuses me. I have a class with a constant and a regular property:
```php
class Car {
const WHEELS = 4;
public $color = 'red';
public function showInfo() {
echo "Wheels: " . self::WHEELS . "\n";
echo "Color: " . $this->color . "\n";
}
}
$car = new Car();
$car->showInfo();
```
Why do I write `self::WHEELS` for the constant, but `$this->color` for the property? What happens if I try to write `self::$color` or `$this::WHEELS`? Does this work with inheritance? For example, if I create a child class
No answers yet.
Log in to leave an answer