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)
__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)
归档时间: |
|
查看次数: |
14034 次 |
最近记录: |