0
0
PHPprogramming~15 mins

Constructor promotion in PHP - Deep Dive

Choose your learning style9 modes available
Overview - Constructor promotion
What is it?
Constructor promotion is a feature in PHP that lets you declare and initialize class properties directly in the constructor parameters. Instead of writing separate lines to declare properties and assign values inside the constructor, you combine both steps in one place. This makes your code shorter and easier to read. It was introduced to simplify class property handling.
Why it matters
Without constructor promotion, you have to write more code to declare properties and assign them inside the constructor, which can be repetitive and error-prone. Constructor promotion saves time and reduces mistakes by combining these steps. It makes classes cleaner and helps developers focus on logic rather than boilerplate code.
Where it fits
Before learning constructor promotion, you should understand basic PHP classes, properties, and constructors. After mastering it, you can explore advanced object-oriented concepts like typed properties, property visibility, and dependency injection.
Mental Model
Core Idea
Constructor promotion lets you declare and initialize class properties in one step by using constructor parameters with visibility keywords.
Think of it like...
It's like ordering a meal where you tell the waiter your drink and food choice at the same time, instead of ordering the drink first and then the food separately.
┌─────────────────────────────┐
│ class Example {             │
│   public function __construct(│
│     private string $name,   │
│     protected int $age      │
│   ) {}                      │
│ }                          │

This replaces:

class Example {
  private string $name;
  protected int $age;

  public function __construct(string $name, int $age) {
    $this->name = $name;
    $this->age = $age;
  }
}
Build-Up - 7 Steps
1
FoundationBasic class properties and constructor
🤔
Concept: How to declare properties and assign them inside a constructor in PHP.
class Person { public string $name; public int $age; public function __construct(string $name, int $age) { $this->name = $name; $this->age = $age; } } $person = new Person('Alice', 30); echo $person->name . ', ' . $person->age;
Result
Alice, 30
Understanding the traditional way of declaring and initializing properties is essential before learning how constructor promotion simplifies this process.
2
FoundationProperty visibility keywords explained
🤔
Concept: Properties can be public, private, or protected, controlling access from outside the class.
class Example { public string $publicProp; private int $privateProp; protected bool $protectedProp; public function __construct(string $pub, int $priv, bool $prot) { $this->publicProp = $pub; $this->privateProp = $priv; $this->protectedProp = $prot; } } $ex = new Example('hello', 42, true); echo $ex->publicProp; // works // echo $ex->privateProp; // error // echo $ex->protectedProp; // error
Result
hello
Knowing visibility is key because constructor promotion requires specifying visibility in the constructor parameters.
3
IntermediateIntroducing constructor promotion syntax
🤔Before reading on: do you think constructor promotion requires separate property declarations? Commit to your answer.
Concept: You can declare and initialize properties directly in the constructor parameters using visibility keywords.
class Person { public function __construct( public string $name, public int $age ) {} } $person = new Person('Bob', 25); echo $person->name . ', ' . $person->age;
Result
Bob, 25
Understanding that constructor promotion combines declaration and assignment reduces boilerplate and makes code cleaner.
4
IntermediateTyped properties with constructor promotion
🤔Before reading on: do you think constructor promotion supports type declarations? Commit to your answer.
Concept: Constructor promotion supports typed properties, enforcing data types directly in constructor parameters.
class Product { public function __construct( private int $id, protected string $name, public float $price ) {} public function getName(): string { return $this->name; } } $product = new Product(1, 'Book', 9.99); echo $product->getName();
Result
Book
Knowing that constructor promotion works with typed properties helps maintain data integrity and clarity.
5
IntermediateVisibility and default values in promotion
🤔
Concept: You can set default values for promoted properties and control their visibility.
class User { public function __construct( public string $username = 'guest', private bool $active = true ) {} public function isActive(): bool { return $this->active; } } $user = new User(); echo $user->username . ', ' . ($user->isActive() ? 'active' : 'inactive');
Result
guest, active
Understanding default values in constructor promotion allows flexible object creation with optional parameters.
6
AdvancedLimitations and edge cases of promotion
🤔Before reading on: do you think constructor promotion can be used with static properties? Commit to your answer.
Concept: Constructor promotion cannot be used for static properties or properties without visibility keywords.
class Test { // This is invalid: // public static int $count; // Constructor promotion requires visibility and non-static public function __construct(public int $id) {} } $test = new Test(5); echo $test->id;
Result
5
Knowing the limits of constructor promotion prevents misuse and errors in class design.
7
ExpertHow constructor promotion affects reflection and serialization
🤔Before reading on: do you think promoted properties behave differently in reflection or serialization? Commit to your answer.
Concept: Promoted properties are treated like normal properties by PHP reflection and serialization, but their declaration is syntactic sugar only.
class Demo { public function __construct(public string $data) {} } $demo = new Demo('info'); $reflection = new ReflectionClass($demo); $props = $reflection->getProperties(); foreach ($props as $prop) { echo $prop->getName() . "\n"; } // Serialization $serialized = serialize($demo); echo $serialized;
Result
data O:4:"Demo":1:{s:4:"data";s:4:"info";}
Understanding that constructor promotion is syntax-only helps experts debug and use advanced PHP features correctly.
Under the Hood
Constructor promotion works by parsing the constructor parameters with visibility keywords and automatically creating class properties with those names and types. At runtime, PHP treats these promoted parameters as if the properties were declared normally and assigned inside the constructor body. This means the promoted properties exist in the class's property table and behave like regular properties.
Why designed this way?
PHP introduced constructor promotion to reduce repetitive boilerplate code common in classes with many properties. Instead of forcing developers to declare properties and write assignment code separately, this design combines both steps for clarity and brevity. Alternatives like separate declarations were more verbose and error-prone, so this approach improves developer experience without changing runtime behavior.
┌───────────────────────────────┐
│ Constructor with promotion     │
│ ┌───────────────────────────┐ │
│ │ __construct(public string $name, int $age) {} │
│ └───────────────────────────┘ │
│             │                 │
│             ▼                 │
│ ┌───────────────────────────┐ │
│ │ PHP creates properties:    │ │
│ │ public string $name;       │ │
│ │ public int $age;           │ │
│ └───────────────────────────┘ │
│             │                 │
│             ▼                 │
│ ┌───────────────────────────┐ │
│ │ Assigns constructor params  │ │
│ │ to properties automatically │ │
│ └───────────────────────────┘ │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does constructor promotion create new runtime behavior or just syntax sugar? Commit to yes or no.
Common Belief:Constructor promotion changes how properties work at runtime and adds new features.
Tap to reveal reality
Reality:Constructor promotion is purely syntax sugar; it does not change runtime behavior or property handling.
Why it matters:Believing it changes runtime can lead to confusion when debugging or using reflection and serialization.
Quick: Can you promote static properties in PHP constructors? Commit to yes or no.
Common Belief:You can use constructor promotion for static properties as well.
Tap to reveal reality
Reality:Constructor promotion does not support static properties; they must be declared separately.
Why it matters:Trying to promote static properties causes syntax errors and wastes time troubleshooting.
Quick: Does constructor promotion allow omitting visibility keywords? Commit to yes or no.
Common Belief:You can omit visibility keywords and still promote properties.
Tap to reveal reality
Reality:Visibility keywords (public, private, protected) are mandatory for constructor promotion.
Why it matters:Omitting visibility causes syntax errors and confusion about property scope.
Quick: Are promoted properties always public by default? Commit to yes or no.
Common Belief:If you don't specify visibility, promoted properties default to public.
Tap to reveal reality
Reality:You must specify visibility explicitly; there is no default for promotion parameters.
Why it matters:Assuming defaults can lead to unexpected access levels and security issues.
Expert Zone
1
Promoted properties are initialized before the constructor body runs, so you cannot override them inside the constructor without reassigning.
2
Reflection treats promoted properties exactly like normal properties, which means tools and libraries work seamlessly with them.
3
Constructor promotion does not support attributes or doc comments on promoted properties directly; you must declare such properties separately.
When NOT to use
Avoid constructor promotion when you need to add complex logic during property initialization or when properties require attributes or annotations. In those cases, declare properties normally and assign them inside the constructor.
Production Patterns
Constructor promotion is widely used in modern PHP frameworks for dependency injection and data transfer objects (DTOs) to reduce boilerplate. It is common in Laravel, Symfony, and other projects to write concise, readable classes.
Connections
Dependency Injection
Constructor promotion simplifies injecting dependencies by declaring them as promoted properties.
Knowing constructor promotion helps understand how modern PHP frameworks inject services cleanly and concisely.
Record Types (in other languages)
Constructor promotion is similar to record types that bundle data with minimal syntax.
Seeing this connection helps appreciate how different languages solve the same problem of concise data containers.
Function Parameter Destructuring (JavaScript)
Both allow unpacking and assigning values in one step, reducing boilerplate.
Understanding this cross-language pattern reveals a common goal: making code shorter and clearer by combining declaration and assignment.
Common Pitfalls
#1Trying to promote a static property inside the constructor.
Wrong approach:class Example { public function __construct(public static int $count) {} }
Correct approach:class Example { public static int $count; public function __construct(int $count) { self::$count = $count; } }
Root cause:Misunderstanding that constructor promotion only works for instance properties, not static ones.
#2Omitting visibility keyword in constructor promotion parameters.
Wrong approach:class User { public function __construct(string $name) {} }
Correct approach:class User { public function __construct(public string $name) {} }
Root cause:Not knowing that visibility keywords are mandatory for constructor promotion.
#3Trying to add attributes or doc comments directly to promoted properties.
Wrong approach:class Product { public function __construct( #[ORMColumn] public string $name ) {} }
Correct approach:class Product { #[ORMColumn] public string $name; public function __construct(string $name) { $this->name = $name; } }
Root cause:Assuming promoted properties support attributes or comments like normal property declarations.
Key Takeaways
Constructor promotion in PHP lets you declare and initialize class properties directly in constructor parameters, reducing boilerplate.
Visibility keywords are required in constructor promotion to define property access levels clearly.
This feature is syntax sugar only; it does not change how properties behave at runtime or with reflection.
Constructor promotion cannot be used for static properties or when attributes are needed on properties.
Understanding constructor promotion helps write cleaner, more maintainable PHP classes and aligns with modern PHP practices.