When to use self and when to use $this in PHP? Difference and examples
Hello everyone! I started learning OOP in PHP and can't understand the difference between `self` and `$this`. Both seem to be used inside a class to access properties and methods, but I keep getting confused.
Here's an example of my code:
```php
class User {
public $name = 'Guest';
public static $count = 0;
public function setName($name) {
$this->name = $name; // why not self?
}
public static function getCount() {
return self::$count; // why not $this?
}
}
```
When I write `$this->name` — it works. But if I write `self::$name` — I get an error. And with the static property it's the opposite: `self::$count` works, but `$this->count` doesn't.
I read the manual, but it's too complicated. Explain in simple terms: when should I use `self::`, and when
No answers yet.
Log in to leave an answer
Blogs
Functional Programming in Go: Principles and Examples
How to Join a List of Strings into CSV in C#: Under the Hood Analysis
How to Catch Multiple Exceptions in C#: A Complete Guide
C# Developer 2025: Complete Roadmap from Beginner to Middle