Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor in PHP

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.

like image 371
Blueberry Avatar asked Mar 21 '17 13:03

Blueberry


People also ask

What is a constructor in PHP?

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 (__)!

What is PHP constructor and destructor?

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.


2 Answers

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
?>
like image 70
node_modules Avatar answered Oct 02 '22 16:10

node_modules


__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!"
like image 28
rap-2-h Avatar answered Oct 02 '22 17:10

rap-2-h