Passing parameters to the constructor
Learn to pass parameters to the constructor and use them at instantiation.
Passing parameters to the constructor
The constructor can take parameters just like a regular function. You write them inside the __construct parentheses:
class User {
public function __construct($name) {
echo "Hello " . $name;
}
}When instantiating, you pass the parameters inside the parentheses on the new line: $user = new User("Alex");. PHP first builds the object, then passes "Alex" to the constructor and runs the method.
Multiple parameters are separated by commas: __construct($name, $age). The call gives them in the same order: new User("Alex", 28).
Call and definition must match
When the constructor has parameters, every new call must supply them. If a parameter is missing, PHP raises an error.
Parameter order matters. For the definition __construct($name, $age), the call new User("Alex", 28) puts the first value into $name and the second into $age. Mix the order and the values land in the wrong place.
You can also give a default value: __construct($name, $role = "user"). Then the call new User("Alex") is valid; $role defaults to "user".
Exercise A two-parameter Product constructor
Define a class named Product. Its constructor should take two parameters with the signature __construct($name, $price). In the body print the product name and price with echo $name . ": " . $price . "\n";. Below the class create an instance with $p = new Product("Coffee", 80);.
Show example solution
public function __construct($name, $price). Body: echo $name . ": " . $price . "\n";. Call: $p = new Product("Coffee", 80);.
Example solution:
<?php
// Define the Product class and add a two-parameter constructor
class Product {
public function __construct($name, $price) {
echo $name . ": " . $price . "\n";
}
}
$p = new Product("Coffee", 80);
Test yourself
-
Complete the call
$user = ____;Show answer
$user = new User("Alex"); -
How do you pass a parameter to the constructor with new?
- Call new User() and pass the parameter separately later
- The constructor takes no parameters, only properties are assigned
- Inside the parentheses as new User("Alex")
- The parameter is written before the class name
Show answer
Inside the parentheses as new User("Alex") — Correct. The values you put in the new operator's parentheses are passed to __construct in order.
-
Match the concepts
- __construct($name)
- single-param constructor
- new User("Alex")
- instantiation with arg
- $name
- constructor parameter variable
- "Alex"
- value passed at call