Mohamed Idris
Posted on June 18, 2024
In PHP, static
and self
are keywords used to refer to properties and methods within classes, but they behave differently in terms of inheritance and late static bindings.
Static
-
Definition: When used inside a class,
static
refers to the class that the method or property is called on, not the class where it is defined. - Usage: Typically used for static properties and methods that are shared across all instances of a class and do not change between instances.
-
Inheritance: Static references using
static
are resolved at run time, which means they refer to the class of the object instance on which the method or property is called, adapting to any subclass that may inherit them dynamically.
Example:
<?php
class Furniture {
protected static $category = 'General';
public static function describe() {
return 'This is a ' . static::$category . ' piece of furniture.';
}
}
class Chair extends Furniture {
protected static $category = 'Chair';
}
echo Furniture::describe(); // Outputs: This is a General piece of furniture.
echo Chair::describe(); // Outputs: This is a Chair piece of furniture.
?>
Self
-
Definition:
self
refers explicitly to the class in which the keyword is used. It is resolved using the class where it is defined, not where it is called. - Usage: Useful for accessing static properties and methods within the same class, especially when you want to ensure that the reference does not change with inheritance.
-
Inheritance: Static references using
self
are resolved early at compile-time and do not change in subclasses.
Example:
<?php
class Furniture {
protected static $category = 'General';
public static function describe() {
return 'This is a ' . self::$category . ' piece of furniture.';
}
}
class Chair extends Furniture {
protected static $category = 'Chair';
}
echo Furniture::describe(); // Outputs: This is a General piece of furniture.
echo Chair::describe(); // Outputs: This is a General piece of furniture.
?>
Conclusion
- Static is used to refer to properties and methods in a way that allows for late static bindings, meaning references can change based on the runtime class.
- Self is used for references that should remain specific to the class where they are defined, ensuring they do not change with inheritance.
Understanding when to use static
vs self
depends on whether you want the reference to adapt to subclasses (static
) or remain fixed at the class where it is defined (self
). Each serves a distinct purpose in PHP's object-oriented programming paradigm.
💖 💪 🙅 🚩
Mohamed Idris
Posted on June 18, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.