Bird
Raised Fist0
PHPprogramming~10 mins

Constructor promotion in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Constructor promotion
Define class with promoted properties
↓
Create object with constructor args
↓
Properties auto-assigned
↓
Use object properties directly
Constructor promotion lets you declare and assign class properties directly in the constructor parameters, simplifying code.
Execution Sample
PHP
<?php
class User {
  public function __construct(public string $name, public int $age) {}
}
$user = new User("Anna", 30);
echo $user->name . ', ' . $user->age;
?>
This code creates a User object with name and age using constructor promotion, then prints the values.
Execution Table
StepActionEvaluationResult
1Define class User with promoted propertiespublic string $name, public int $ageProperties declared and constructor created
2Create new User object with args ('Anna', 30)$name = 'Anna', $age = 30Object $user created
3Assign constructor args to properties$this->name = 'Anna', $this->age = 30Properties set automatically
4Access $user->nameReturns 'Anna'Output: Anna
5Access $user->ageReturns 30Output: 30
6Concatenate and echo'Anna, 30'Printed: Anna, 30
💡 End of script after printing user name and age
Variable Tracker
VariableStartAfter Step 2After Step 3Final
$nameundefined'Anna''Anna'undefined
$ageundefined3030undefined
$user->nameundefinedundefined'Anna''Anna'
$user->ageundefinedundefined3030
Key Moments - 3 Insights
Why don't we see property declarations inside the class body?
Because constructor promotion declares and assigns properties directly in the constructor parameters, so separate declarations are not needed (see Step 1 and Step 3).
How are the constructor arguments assigned to properties automatically?
The 'public' keyword before parameters tells PHP to create properties and assign values automatically during object creation (Step 3 shows this).
Can we access properties like $user->name right after creating the object?
Yes, because properties are set during construction, so accessing them after Step 3 returns the assigned values.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $user->age after Step 3?
A30
Bundefined
C0
Dnull
💡 Hint
Check the 'Result' column in Step 3 where properties are assigned.
At which step are the constructor arguments assigned to the object properties?
AStep 2
BStep 4
CStep 3
DStep 1
💡 Hint
Look for the step describing property assignment in the execution table.
If we remove 'public' from the constructor parameters, what changes in the execution?
AObject creation will fail
BProperties won't be created or assigned automatically
CProperties will still be created automatically
DConstructor will not run
💡 Hint
Recall the role of 'public' in constructor promotion from the key moments.
Concept Snapshot
Constructor promotion in PHP lets you declare and assign class properties directly in the constructor parameters.
Use visibility keywords (public/private/protected) before parameters.
This removes the need for separate property declarations and assignments.
Example: __construct(public string $name, public int $age) {}
Properties are set automatically when creating an object.
Full Transcript
Constructor promotion is a PHP feature that simplifies class property declaration and assignment. Instead of declaring properties separately and assigning them inside the constructor, you write the properties directly in the constructor parameters with visibility keywords like public. When you create an object, PHP automatically creates those properties and assigns the passed values. For example, class User with __construct(public string $name, public int $age) {} creates properties name and age and sets them when you do new User('Anna', 30). You can then access $user->name and $user->age directly. This reduces boilerplate code and makes classes cleaner.

Practice

(1/5)
1. What is the main benefit of using constructor promotion in PHP classes?
easy
A. It automatically generates getter and setter methods for properties.
B. It allows declaring and assigning properties in one step inside the constructor.
C. It enforces strict typing on all class properties.
D. It makes the class immutable by default.

Solution

  1. Step 1: Understand constructor promotion purpose

    Constructor promotion lets you declare and assign properties directly in the constructor parameters.
  2. Step 2: Compare options

    Only It allows declaring and assigning properties in one step inside the constructor. correctly describes this benefit. Options B, C, and D describe unrelated features.
  3. Final Answer:

    It allows declaring and assigning properties in one step inside the constructor. -> Option B
  4. Quick Check:

    Constructor promotion = Declare and assign properties together [OK]
Hint: Constructor promotion combines property declaration and assignment [OK]
Common Mistakes:
  • Thinking it auto-generates getters/setters
  • Confusing with immutability
  • Assuming it enforces typing
2. Which of the following is the correct syntax for constructor promotion in PHP?
easy
A. public function __construct(private string $name, int $age) {}
B. public function __construct(var $name, var $age) {}
C. public function __construct(string $name, int $age) { $this->name = $name; }
D. public function __construct(private string $name, private int $age) {}

Solution

  1. Step 1: Identify visibility keywords in constructor parameters

    Constructor promotion requires visibility keywords like private, protected, or public before parameters.
  2. Step 2: Check each option

    public function __construct(private string $name, private int $age) {} uses private for both parameters, which is correct. public function __construct(private string $name, int $age) {} misses visibility for $age. public function __construct(string $name, int $age) { $this->name = $name; } is normal assignment, not promotion. public function __construct(var $name, var $age) {} uses invalid 'var' keyword.
  3. Final Answer:

    public function __construct(private string $name, private int $age) {} -> Option D
  4. Quick Check:

    Visibility + parameter = constructor promotion [OK]
Hint: Use visibility keywords on constructor parameters for promotion [OK]
Common Mistakes:
  • Omitting visibility keyword
  • Using invalid keywords like var
  • Confusing promotion with manual assignment
3. What will be the output of the following PHP code?
class User {
    public function __construct(private string $name, private int $age) {}
    public function getInfo() {
        return "$this->name is $this->age years old.";
    }
}
$user = new User('Alice', 30);
echo $user->getInfo();
medium
A. Alice is 30 years old.
B. Error: Cannot access private property
C. 30 is Alice years old.
D. Syntax error

Solution

  1. Step 1: Understand property promotion and access

    The properties $name and $age are private but accessible inside class methods like getInfo().
  2. Step 2: Analyze getInfo() output

    It returns a string combining $name and $age values. Since $user is created with 'Alice' and 30, output is "Alice is 30 years old."
  3. Final Answer:

    Alice is 30 years old. -> Option A
  4. Quick Check:

    Private properties accessible inside class = correct output [OK]
Hint: Private promoted properties accessible inside class methods [OK]
Common Mistakes:
  • Assuming private properties are inaccessible inside class
  • Mixing order of name and age in output
  • Expecting syntax error
4. Identify the error in this PHP class using constructor promotion:
class Product {
    public function __construct(private $name, private int $price) {}
}
medium
A. Cannot use private keyword in constructor parameters.
B. Price parameter should be string, not int.
C. Missing type declaration for $name parameter.
D. Constructor promotion requires public visibility only.

Solution

  1. Step 1: Check parameter declarations

    The $name parameter lacks a type declaration, which is required for constructor promotion to be clear and strict.
  2. Step 2: Validate other options

    Private visibility is allowed, int type for price is valid, and promotion supports all visibility levels.
  3. Final Answer:

    Missing type declaration for $name parameter. -> Option C
  4. Quick Check:

    All promoted parameters need type declarations [OK]
Hint: All promoted parameters must have types declared [OK]
Common Mistakes:
  • Omitting type for promoted parameters
  • Thinking only public visibility allowed
  • Confusing parameter types
5. You want to create a PHP class Book with promoted properties title (string), author (string), and pages (int). You also want to add a method summary() that returns a string like "Title by Author, Pages pages.". Which of the following is the correct complete class code?
hard
A. class Book { public function __construct(public string $title, public string $author, public int $pages) {} public function summary() { return "$this->title by $this->author, $this->pages pages."; } }
B. class Book { public string $title; public string $author; public int $pages; public function __construct($title, $author, $pages) { $this->title = $title; $this->author = $author; $this->pages = $pages; } public function summary() { return "$title by $author, $pages pages."; } }
C. class Book { public function __construct(string $title, string $author, int $pages) {} public function summary() { return "$this->title by $this->author, $this->pages pages."; } }
D. class Book { public function __construct(private string $title, private string $author, private int $pages) {} public function summary() { return "$title by $author, $pages pages."; } }

Solution

  1. Step 1: Check constructor promotion syntax

    class Book { public function __construct(public string $title, public string $author, public int $pages) {} public function summary() { return "$this->title by $this->author, $this->pages pages."; } } correctly uses public visibility with types in constructor parameters to promote properties.
  2. Step 2: Verify summary() method access and string

    class Book { public function __construct(public string $title, public string $author, public int $pages) {} public function summary() { return "$this->title by $this->author, $this->pages pages."; } } uses $this->property to access promoted properties and returns the correct formatted string.
  3. Step 3: Analyze other options

    class Book { public string $title; public string $author; public int $pages; public function __construct($title, $author, $pages) { $this->title = $title; $this->author = $author; $this->pages = $pages; } public function summary() { return "$title by $author, $pages pages."; } } uses manual assignment but summary() incorrectly uses variables without $this->. class Book { public function __construct(string $title, string $author, int $pages) {} public function summary() { return "$this->title by $this->author, $this->pages pages."; } } promotes parameters but does not assign them to properties. class Book { public function __construct(private string $title, private string $author, private int $pages) {} public function summary() { return "$title by $author, $pages pages."; } } uses private properties but summary() accesses variables without $this->, causing errors.
  4. Final Answer:

    Option A code with public promoted properties and correct summary() -> Option A
  5. Quick Check:

    Promotion + correct property access = class Book { public function __construct(public string $title, public string $author, public int $pages) {} public function summary() { return "$this->title by $this->author, $this->pages pages."; } } [OK]
Hint: Use visibility + $this->property in methods for promoted properties [OK]
Common Mistakes:
  • Forgetting $this-> in methods
  • Not assigning promoted properties properly
  • Mixing private properties with wrong access
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard