Classes and Objects
A class is a blueprint that defines the properties (state) and methods (behavior) shared by all objects created from it, and an object is a single instance of that blueprint created with the new keyword. PHP's object model has matured substantially since PHP 5, adding typed properties (PHP 7.4), constructor property promotion (PHP 8.0), and readonly properties (PHP 8.1), all of which reduce boilerplate while making class contracts more explicit and safer to work with. Every object carries its own independent copy of instance properties, while methods are shared and operate on whichever object called them, accessible inside the method body via the $this pseudo-variable.
Cricket analogy: A bowling coaching manual is the blueprint every fast bowler learns from, but each bowler like Bumrah or Starc is a distinct instance with his own run-up and grip, referenced as 'the bowler himself' during the over.
Declaring Properties, Visibility, and Constructors
Properties and methods each declare a visibility: public (accessible from anywhere), protected (accessible within the class and its subclasses), or private (accessible only within the declaring class itself). The constructor, a special method named __construct(), runs automatically when an object is created and is the conventional place to initialize required state. PHP 8.0's constructor property promotion lets you declare and assign typed properties directly in the constructor's parameter list, eliminating the repetitive pattern of declaring a property and then assigning $this->prop = $prop for every parameter.
Cricket analogy: A public shot like the cover drive is one any batter can attempt openly, a protected sweep passes only within a coaching lineage, and a private grip adjustment stays known only to that batter, set the moment they walk in via their 'starting stance.'
final class Product
{
public function __construct(
public readonly string $sku,
public readonly string $name,
private float $price,
) {}
public function priceWithTax(float $rate = 0.2): float
{
return round($this->price * (1 + $rate), 2);
}
}
$item = new Product('SKU-100', 'Keyboard', 49.99);
echo $item->name; // Keyboard
echo $item->priceWithTax(); // 59.99Static Members and readonly Properties
Members declared static belong to the class itself rather than to any individual instance, accessed via ClassName::$property or ClassName::method(), and are commonly used for factory methods, counters, or shared configuration. A readonly property (PHP 8.1+) can be assigned exactly once, only from within the declaring class's scope (typically the constructor), and any later assignment attempt throws an Error, making it an effective tool for building genuinely immutable value objects without external setter discipline.
Cricket analogy: A team's shared kit sponsor logo is like a static property, 'Team::$sponsor,' the same for every player rather than each individual, while a player's date of debut is readonly, set once and immutable no matter how their career unfolds.
class Counter
{
private static int $instances = 0;
public function __construct()
{
self::$instances++;
}
public static function total(): int
{
return self::$instances;
}
}
new Counter();
new Counter();
echo Counter::total(); // 2Encapsulation in Practice
Encapsulation means exposing a deliberate, minimal public interface while hiding internal implementation details behind private or protected visibility, which lets a class change its internals freely without breaking code that depends on it. Well-designed classes typically favor private properties accessed through explicit, purposeful methods rather than exposing raw mutable state, and use readonly or the absence of setters to signal which data should never change after construction.
Cricket analogy: A captain reveals only the final batting order to the media, the public interface, while keeping selection debates private within the dressing room, letting strategy change internally without the public order needing explanation.
Constructor property promotion is purely syntactic sugar: public function __construct(public readonly string $sku) compiles to exactly the same property declaration and assignment as writing it out manually. It exists to cut repetitive boilerplate in classes with many simple constructor-assigned properties, not to change PHP's underlying object semantics.
A common mistake is declaring a property public by default out of convenience. This removes the class's ability to validate or control how that state changes, effectively making every consumer of the object a potential source of invalid state. Default to private (or protected for subclass access) and expose only the specific getters, setters, or behavior methods that are genuinely needed.
- A class defines shared structure (properties) and behavior (methods); an object is one instance created with
new. - Visibility keywords — public, protected, private — control where properties and methods can be accessed from.
- __construct() runs automatically on instantiation; constructor property promotion (PHP 8.0+) declares and assigns properties in one step.
- readonly properties (PHP 8.1+) can be set only once, enabling true immutability for value objects.
- static properties and methods belong to the class itself, not to individual instances, and are accessed via ClassName::.
- Favor private state with a deliberate public interface (encapsulation) over exposing raw public properties.
Practice what you learned
1. What does constructor property promotion in PHP 8.0 eliminate the need for?
2. What happens if you attempt to assign a value to a readonly property outside of its declaring class's initialization scope?
3. How are static properties accessed from outside the class?
4. Which visibility level allows access from the declaring class and its subclasses, but not from outside code?
5. Why is defaulting all class properties to public generally considered poor practice?
Was this page helpful?
You May Also Like
Inheritance and Interfaces
Understand how PHP classes extend one another via single inheritance and implement contracts via interfaces, including method overriding rules.
Abstract Classes and Polymorphism
Abstract classes define a partial implementation and a contract that subclasses must complete, enabling polymorphic code that treats different concrete types uniformly.
Magic Methods
Magic methods are special, double-underscore-prefixed hooks PHP invokes automatically for events like object construction, property access, and string conversion.
Type Declarations and Strict Types
PHP supports optional scalar and object type declarations on parameters, return values, and properties, with strict_types controlling how aggressively the engine coerces mismatched values.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics