Concept Flow - Constructor method
Create object
Call __construct()
Initialize properties
Object ready for use
When a new object is created, PHP automatically calls the __construct() method to set up the object.
<?php class Car { public $color; public function __construct($color) { $this->color = $color; } } $myCar = new Car('red'); echo $myCar->color; ?>
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Create new Car object with 'red' | Calls __construct('red') | Property color set to 'red' |
| 2 | Access $myCar->color | Returns 'red' | Output: red |
| 3 | End of script | No more code | Execution stops |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| $myCar | null | object Car with color='red' | object Car with color='red' | object Car with color='red' |
| $myCar->color | undefined | 'red' | 'red' | 'red' |
PHP Constructor Method (__construct):
- Special method called automatically when creating an object.
- Used to initialize object properties.
- Syntax: public function __construct(parameters) { ... }
- Use $this->property to set values inside.
- If missing, object is created without automatic setup.