🐶
PHP

PHP self vs $this: When to Use Each

By Filip on 10/16/2024

Learn when to use 'self' vs. '$this' in PHP to effectively access static and instance members within your classes.

PHP self vs $this: When to Use Each

Table of Contents

Introduction

In object-oriented programming with PHP, understanding the difference between $this and self is crucial, especially when dealing with static properties and methods. These keywords help you interact with different aspects of a class and its instances.

Step-by-Step Guide

$this refers to the current object instance, while self refers to the current class itself.

Think of it like this:

  • $this is like saying "me" - it's about the specific object you're working with.
  • self is like saying "our kind" - it's about the class that the object belongs to.

Here's a simple example:

class MyClass {
    public static $myStatic = 'static value';
    public $myVar = 'instance value';

    public function myMethod() {
        echo $this->myVar; // Accessing instance property
        echo self::$myStatic; // Accessing static property
    }
}

You would use self when you want to access static properties or methods of a class from within the class itself.

On the other hand, new self() and new static() are used for creating new instances of a class.

  • new self() will always create a new instance of the same class it's called from.
  • new static() is more flexible, especially with inheritance. If you call new static() from a child class, it will create a new instance of the child class, not the parent class.

Late static binding, achieved with static, allows you to dynamically determine which class is being referred to during runtime, which is particularly useful when working with inheritance.

Code Example

The code defines a base class 'Vehicle' and a subclass 'Car' to illustrate PHP's inheritance and static keyword behavior. The Vehicle class sets up basic vehicle properties like brand and engine type. The Car class inherits these properties but overrides the engine type. Both classes have methods to describe themselves and the Car class includes a static method to create new Car instances. The example demonstrates how PHP handles static properties and methods within an inheritance hierarchy, showcasing the concept of late static binding.

class Vehicle {
    protected static $engineType = 'Gasoline';
    public $brand;

    public function __construct($brand) {
        $this->brand = $brand;
    }

    public static function getEngineType() {
        return self::$engineType; // Refers to Vehicle's engineType
    }

    public function describe() {
        echo "This is a {$this->brand} vehicle with a " . self::getEngineType() . " engine.\n";
    }
}

class Car extends Vehicle {
    protected static $engineType = 'Electric'; // Overriding engine type

    public static function createCar($brand) {
        return new static($brand); // Creates a new instance of 'Car'
    }
}

$myCar = Car::createCar('Tesla');
$myCar->describe(); // Output: This is a Tesla vehicle with an Electric engine.

$myVehicle = new Vehicle('Ford');
$myVehicle->describe(); // Output: This is a Ford vehicle with a Gasoline engine. 

Explanation:

  1. Vehicle Class:

    • self::$engineType: Accessed within the class context, self refers to Vehicle, so it accesses Vehicle's $engineType.
    • $this->brand: $this refers to the specific instance of the Vehicle object.
  2. Car Class:

    • static::$engineType: This demonstrates late static binding. Even though called from the Vehicle class's describe() method, static ensures that the $engineType accessed is the one associated with the Car class.
    • new static($brand): This is where the power of late static binding shines. Even though this method is within the Car class, if a subclass of Car were to call this method, new static() would create an instance of that subclass, not Car.

Key Points:

  • $this: Instance-specific, refers to the object itself.
  • self: Class-specific, always refers to the class where it's used.
  • static: Enables late static binding, making code more flexible and adaptable to inheritance.

This example highlights the differences and use cases of $this, self, and static in PHP, especially in the context of inheritance.

Additional Notes

  • Visibility: Remember that $this can access both public and private/protected members of the current object. self (and static) are subject to the same visibility rules when accessing properties and methods.

  • Constants: You can use self:: to access class constants from within the class, as they behave similarly to static properties.

  • Inheritance Context: When a subclass inherits from a parent class, self within the subclass still refers to the subclass itself, not the parent class. This is where static becomes crucial for late static binding.

  • Abstract Classes and Interfaces: You cannot instantiate abstract classes directly, so new self() within an abstract class wouldn't make sense. However, self is still used to refer to static members within the abstract class itself. Interfaces cannot have static members, so self is not typically used within them.

  • Performance: There's a slight performance advantage to using self:: over static:: because late static binding requires a runtime lookup. However, the flexibility and correctness offered by static often outweigh this minor performance difference.

  • Best Practices:

    • Favor static:: over self:: when you need the flexibility of late static binding, especially when working with inheritance.
    • Use $this when you need to work with the specific instance of the object.
    • Write clear and concise code that makes your intent obvious when using these keywords.

Summary

Keyword Refers to Usage Example
$this Current object instance Accessing instance properties and methods within the object $this->myVar
self Current class itself Accessing static properties and methods within the class self::$myStatic
new self() Current class Creating a new instance of the same class
new static() Class being called from Creating a new instance of the class the method is called from (useful with inheritance)
static (Late Static Binding) Dynamically determined class Allows for dynamic class resolution during runtime, especially useful with inheritance

In short:

  • Use $this for "me" (the specific object).
  • Use self for "our kind" (the class itself).
  • new self() creates an instance of the same class.
  • new static() creates an instance of the class it's called from (even if it's a child class).
  • static enables dynamic class resolution during runtime.

Conclusion

By understanding these concepts, you can write more robust and flexible object-oriented code in PHP, especially when leveraging the power of inheritance. Remember to consult the provided resources and official PHP documentation for more in-depth explanations and advanced use cases. Happy coding!

References

Should i spray bare metal with epoxy primer before adding bondo body filler or do yall think its ok to just throw it over metal. Anyone apply it to bare metal and then years later go back and sand it away and see if there was...

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait