17

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Blueberry
  • 363
  • 1
  • 2
  • 10
  • 6
    `__construct` can take params the same as any other method can. – Jonnix Mar 21 '17 at 13:57
  • You must be reading the wrong books and docs - constructors can take as many parameters as you define – WillardSolutions Mar 21 '17 at 13:59
  • 1
    When in doubt - just read up on stuff like this in the official documentation, instead of relying on 3rd-party resources. http://php.net/manual/en/language.oop5.decon.php – CBroe Mar 21 '17 at 14:00
  • Actually I wonder what you mean by "the parameters declared in the class"... A class has no declared parameters, only methods (functions) have. The constructor is such a method. It will take any parameters declared in its implementation. – arkascha Mar 21 '17 at 14:03

2 Answers2

21

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
?>
node_modules
  • 4,790
  • 6
  • 21
  • 37
5

__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!"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rap-2-h
  • 30,204
  • 37
  • 167
  • 263