Question
In PHP 5, what is the difference between using self and $this?
When should each one be used?
For example, how do they differ when accessing methods or properties inside a class?
Short Answer
By the end of this page, you will understand the difference between self and $this in PHP, how static context differs from instance context, and when each form should be used to access methods and properties inside a class.
Concept
self and $this are both used inside PHP classes, but they refer to different things.
$thisrefers to the current object instance.selfrefers to the current class itself.
This matters because PHP separates instance members from static members:
- Instance properties and methods belong to a specific object created from a class.
- Static properties and methods belong to the class itself, not to any one object.
$this means “this object”
Use $this when you want to work with data or methods that belong to a particular object.
class User {
public $name;
public function setName($name) {
$this->name = $name;
}
public function greet() {
return "Hello, " . $this->name;
}
}
Here, $this->name refers to the name property of the current User object.
self means “this class”
Use self when referring to static properties, static methods, or class constants defined on the same class.
class MathHelper {
public static function add($a, $b) {
return $a + $b;
}
public static function double($value) {
return self::add($value, $value);
}
}
Here, self::add() calls a static method on the class, not on an object instance.
Why this distinction matters
In real programs:
- Objects hold state, such as a user name, cart items, or form data.
- Static members hold shared behavior or class-level values, such as utility methods, counters, or configuration defaults.
Trying to use $this in a static method will fail because there is no object instance there. Likewise, using self to access non-static properties or methods is incorrect because those belong to an object, not the class itself.
Mental Model
Think of a class as a blueprint for houses, and objects as the actual houses built from that blueprint.
$thismeans: this specific house.selfmeans: the blueprint itself.
If you want to know the color of the kitchen in one house, you use $this because that belongs to a specific house.
If you want to read a rule written on the blueprint, such as a standard ceiling height shared by all houses, you use self.
So:
$this= object-level accessself= class-level access
Syntax and Examples
Core syntax
Accessing instance members with $this
class Person {
public $name = "";
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
- Use
->with$this - Works with non-static properties and methods
Accessing static members with self
class Counter {
public static $count = 0;
public static function increment() {
self::$count++;
}
}
- Use
::withself - Works with static properties, static methods, and constants
Example: $this
class Car {
public $brand;
public function __construct($brand) {
$this->brand = $brand;
}
public function describe() {
return "Car brand: " . $this->brand;
}
}
$car = new Car("Toyota");
echo $car->describe();
$this->brand refers to the brand of that specific Car object.
Example: self
class Config {
public static $appName = "My App";
public static function getAppName() {
return self::$appName;
}
}
echo Config::getAppName();
self::$appName refers to a class-level property shared by the class.
Example: using both correctly
class VisitorCounter {
public $visitorName;
public static $totalVisitors = 0;
public function __construct($visitorName) {
$this->visitorName = $visitorName;
self::$totalVisitors++;
}
public function getVisitorName() {
return $this->visitorName;
}
public static function getTotalVisitors() {
return self::$totalVisitors;
}
}
$a = new VisitorCounter("Alice");
$b = new VisitorCounter("Bob");
echo $a->getVisitorName(); // Alice
echo VisitorCounter::getTotalVisitors(); // 2
Here:
$this->visitorNameis per objectself::$totalVisitorsis shared across all objects
Step by Step Execution
Consider this example:
class ScoreBoard {
public $player;
public static $gamesPlayed = 0;
public function __construct($player) {
$this->player = $player;
self::$gamesPlayed++;
}
public function getPlayer() {
return $this->player;
}
public static function getGamesPlayed() {
return self::$gamesPlayed;
}
}
$game1 = new ScoreBoard("Anna");
$game2 = new ScoreBoard("Ben");
echo $game1->getPlayer();
echo ScoreBoard::getGamesPlayed();
Step by step
- The class
ScoreBoardis defined. - It has:
- an instance property:
$player - a static property:
$gamesPlayed
- an instance property:
new ScoreBoard("Anna")creates the first object.- Inside
__construct():$this->player = $playerstores"Anna"in that object.self::$gamesPlayed++increases the class-wide counter from0to1.
new ScoreBoard("Ben")creates a second object.- Inside that constructor:
$this->player = $playerstores"Ben"in the second object.self::$gamesPlayed++increases the shared counter from1to2.
$game1->getPlayer()returns"Anna"because it reads from the first object's$playerproperty using$this.ScoreBoard::getGamesPlayed()returns2because it reads the class-level static property usingself.
Key observation
Each object gets its own $player, but all objects share the same self::$gamesPlayed.
Real World Use Cases
$this and self appear often in real PHP applications.
Common uses of $this
Object state
class SessionUser {
public $email;
public function __construct($email) {
$this->email = $email;
}
}
Each logged-in user object has its own email.
Working with instance methods
class Order {
public function calculateTotal() {
return 100;
}
public function printInvoice() {
return "Total: " . $this->calculateTotal();
}
}
$this is used because calculateTotal() depends on the current order.
Common uses of self
Shared counters
class Job {
public static $created = 0;
public function __construct() {
self::$created++;
}
}
Useful for tracking how many objects were created.
Utility behavior inside a class
class TextTools {
public static function trimText($text) {
return trim($text);
}
public static function normalize($text) {
return self::trimText(strtolower($text));
}
}
Class constants
class ApiConfig {
const VERSION = 'v1';
public static function getVersion() {
return self::VERSION;
}
}
This is useful for fixed values that belong to the class definition.
Real Codebase Usage
In real codebases, developers usually choose between $this and self based on whether they are writing object behavior or class-level behavior.
$this in application code
Instance services and models
class Product {
private $price;
public function __construct($price) {
$this->price = $price;
}
public function isExpensive() {
return $this->price > 100;
}
}
This is common in domain models, entities, and service objects.
Chaining methods
class QueryBuilder {
public function where($field, $value) {
// store condition
return $this;
}
}
Returning $this allows fluent APIs.
self in shared class logic
Factory helpers and internal static helpers
class SlugGenerator {
public static function clean($text) {
return strtolower(trim($text));
}
public static function make($text) {
return str_replace(' ', '-', self::clean($text));
}
}
Validation rules or defaults
class UploadRules {
const MAX_FILE_SIZE = 1048576;
public static function isValidSize($size) {
return $size <= self::MAX_FILE_SIZE;
}
}
Common patterns
- Use
$thisfor object state and behavior. - Use
selffor static helpers, constants, and class-wide counters. - Inside static methods, use
self, not$this. - Inside instance methods, you can use
$this; you may also call static members withselfif appropriate.
In many real projects, developers avoid overusing static methods for logic that depends on changing object state. If data belongs to one object, $this is usually the better choice.
Common Mistakes
1. Using $this inside a static method
This is a very common error.
Broken code
class Test {
public $name = "Sam";
public static function showName() {
return $this->name;
}
}
This fails because a static method does not have an object instance.
Fix
Either make the method non-static:
class Test {
public $name = "Sam";
public function showName() {
return $this->name;
}
}
Or make the property static if it truly belongs to the class:
class Test {
public static $name = "Sam";
public static function showName() {
return self::$name;
}
}
2. Using self for a non-static property
Broken code
class Test {
public $name = "Sam";
public function showName() {
return self::$name;
}
}
$name is not static, so self::$name is wrong.
Fix
class Test {
public $name = "Sam";
public function showName() {
return $this->name;
}
}
3. Confusing -> and ::
- Use
->with objects and$this - Use
::withself, class names, and static members
Broken code
self->method();
$this::method();
Correct usage
self::method();
$this->method();
4. Making something static when it should be instance-based
Beginners sometimes make properties static just to access them more easily.
Problem
If each object should have its own value, static is the wrong choice.
class User {
public static $name;
}
Now all users share one $name, which is usually not what you want.
Better
class User {
public $name;
}
5. Forgetting that static data is shared
A static property is shared across all objects of the class. Changing it in one place affects all uses of that class.
Comparisons
| Concept | $this | self |
|---|---|---|
| Refers to | Current object instance | Current class |
| Used for | Non-static properties and methods | Static properties, static methods, constants |
| Syntax | $this->property, $this->method() | self::$property, self::method(), self::CONSTANT |
| Requires an object? | Yes | No |
| Available in static methods? | No | Yes |
| Shared across all objects? | No | Static members accessed by self are shared |
$this vs static
In PHP, you may also see static::.
self::refers to the class where the code is written.static::supports late static binding in inheritance.
For a beginner, the main thing to remember is:
- Use
$thisfor instance members - Use
selffor members that belong to the class itself
Instance method vs static method
| Feature | Instance Method | Static Method |
|---|---|---|
| Called on | Object | Class |
Can use $this | Yes | No |
| Best for | Object-specific behavior | Shared/helper behavior |
Example:
class Example {
public function instanceMethod() {
return $this->getValue();
}
public static function staticMethod() {
return self::helper();
}
private function getValue() {
return 1;
}
private static function helper() {
return 2;
}
}
Cheat Sheet
Quick rules
- Use
$thisfor instance properties and methods - Use
selffor static properties, static methods, and constants $thisuses->selfuses::$thisis only available when an object existsselfworks in static methods
Syntax
$this->property;
$this->method();
self::$property;
self::method();
self::CONSTANT;
Remember
public $name;→ access with$this->namepublic static $count;→ access withself::$countconst VERSION = '1.0';→ access withself::VERSION
Common decision guide
Ask:
- Does this belong to one object?
- Use
$this
- Use
- Does this belong to the class itself or all objects collectively?
- Use
self
- Use
Fast examples
class Demo {
public $name = "A";
public static $count = 0;
const TYPE = "demo";
public function showName() {
return $this->name;
}
public static function showCount() {
return self::$count;
}
public static function showType() {
return self::TYPE;
}
}
Edge case to remember
You cannot use $this inside a static method.
FAQ
What is the difference between self and $this in PHP?
$this refers to the current object instance. self refers to the current class and is used for static members and constants.
Can I use $this in a static method in PHP?
No. Static methods do not have an object instance, so $this is not available there.
When should I use self:: in PHP?
Use self:: when accessing static properties, static methods, or class constants from within the same class.
When should I use $this-> in PHP?
Use $this-> when accessing non-static properties or methods that belong to the current object.
Is self the same as a static property or static method?
No. self is the keyword used to refer to the class. It is commonly used to access static members, but it is not itself a property or method.
Can an instance method use self?
Yes. An instance method can access static members with self::, but it should use $this-> for instance members.
Are static properties shared between all objects?
Yes. A static property belongs to the class, so all objects of that class share the same value.
Mini Project
Description
Build a small PHP class that models a page visit tracker. This project demonstrates the difference between object-specific data and class-wide shared data. Each visit object should store its own page name, while the class should keep a shared count of how many visits have been created.
Goal
Create a class where $this stores per-object page data and self tracks the total number of visits across all objects.
Requirements
[ "Create a class with one instance property for the page name.", "Add one static property to count total visits.", "Increment the static counter whenever a new object is created.", "Add an instance method to return the page name.", "Add a static method to return the total number of visits." ]
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.