php中的构造函数

Blu*_*ry 9 php methods constructor class

我想知道php中的构造函数方法是否接受类中声明的参数,就像我在多个站点和书籍中看到的那样,在php文档中,函数函数__construct()不带参数

提前致谢

Var*_*ble 9

PHP构造函数可以像其他函数一样获取参数.不需要向__construct()函数添加参数,例如:

示例1:没有参数

<?php
class example {
    public $var;
    function __construct() {
        $this->var = "My example.";
    }
}

$example = new example;
echo $example->var; // Prints: My example.
?>
Run Code Online (Sandbox Code Playgroud)

例2:带参数

<?php
class example {
    public $var;
    function __construct($param) {
        $this->var = $param;
    }
}

$example = new example("Custom parameter");
echo $example->var; // Prints: Custom parameter
?>
Run Code Online (Sandbox Code Playgroud)


rap*_*2-h 5

__construct可以带参数。根据官方文档,这个方法签名是:

void __construct ([ mixed $args = "" [, $... ]] )
Run Code Online (Sandbox Code Playgroud)

所以它似乎可以带参数!

如何使用它:

class MyClass {
    public function __construct($a) {
        echo $a;
    }
}

$a = new MyClass('Hello, World!'); // Will print "Hello, World!"
Run Code Online (Sandbox Code Playgroud)