Question

PHP self vs $this: Difference, Usage, and When to Use Each

phpclassoopscope

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.

  • $this refers to the current object instance.
  • self refers 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.

  • $this means: this specific house.
  • self means: 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 access
  • self = class-level access
Take Quiz

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 :: with self
  • 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->visitorName is per object
  • self::$totalVisitors is 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

  1. The class ScoreBoard is defined.
  2. It has:
    • an instance property: $player
    • a static property: $gamesPlayed
  3. new ScoreBoard("Anna") creates the first object.
  4. Inside __construct():
    • $this->player = $player stores "Anna" in that object.
    • self::$gamesPlayed++ increases the class-wide counter from 0 to 1.
  5. new ScoreBoard("Ben") creates a second object.
  6. Inside that constructor:
    • $this->player = $player stores "Ben" in the second object.
    • self::$gamesPlayed++ increases the shared counter from 1 to 2.
  7. $game1->getPlayer() returns "Anna" because it reads from the first object's $player property using $this.
  8. ScoreBoard::getGamesPlayed() returns 2 because it reads the class-level static property using self.

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.

Take Quiz

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 $this for object state and behavior.
  • Use self for 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 with self if 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 :: with self, 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$thisself
Refers toCurrent object instanceCurrent class
Used forNon-static properties and methodsStatic properties, static methods, constants
Syntax$this->property, $this->method()self::$property, self::method(), self::CONSTANT
Requires an object?YesNo
Available in static methods?NoYes
Shared across all objects?NoStatic 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 $this for instance members
  • Use self for members that belong to the class itself

Instance method vs static method

FeatureInstance MethodStatic Method
Called onObjectClass
Can use $thisYesNo
Best forObject-specific behaviorShared/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;
    }
}
Take Quiz

Cheat Sheet

Quick rules

  • Use $this for instance properties and methods
  • Use self for static properties, static methods, and constants
  • $this uses ->
  • self uses ::
  • $this is only available when an object exists
  • self works in static methods

Syntax

$this->property;
$this->method();

self::$property;
self::method();
self::CONSTANT;

Remember

  • public $name; → access with $this->name
  • public static $count; → access with self::$count
  • const VERSION = '1.0'; → access with self::VERSION

Common decision guide

Ask:

  1. Does this belong to one object?
    • Use $this
  2. Does this belong to the class itself or all objects collectively?
    • Use self

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.

Take Quiz

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." ]

Take Quiz

Keep learning

Related questions

View more