Does a constructor method in PHP take the parameters declared in the class or not?
I've seen on multiple sites and books and in the PHP documentation that the function function __construct() doesn't take any parameters.
A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!
Constructors: Constructors are called when an object is created from a class. Destructors: Destructors are called when an object destructs. Usually, it is when the script ends.
The PHP constructor can take parameters like the other functions can. It's not required to add parameters to the __construct()
function, for example:
Example 1: Without parameters
<?php
class example {
public $var;
function __construct() {
$this->var = "My example.";
}
}
$example = new example;
echo $example->var; // Prints: My example.
?>
Example 2: with parameters
<?php
class example {
public $var;
function __construct($param) {
$this->var = $param;
}
}
$example = new example("Custom parameter");
echo $example->var; // Prints: Custom parameter
?>
__construct
can take parameters. According to the official documentation, this method signature is:
void __construct ([ mixed $args = "" [, $... ]] )
So it seems it can take parameters!
How to use it:
class MyClass {
public function __construct($a) {
echo $a;
}
}
$a = new MyClass('Hello, World!'); // Will print "Hello, World!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With