在阅读PHP构造函数时,我在this页面上看到了以下示例。
<?php
class MyClass {
// use a unique id for each derived constructor,
// and use a null reference to an array,
// for optional parameters
function __construct($id="", $args=null) {
// parent constructor called first ALWAYS
/*Remaining code here*/
}
}
我无法理解为什么$id
设置为""
而$args
设置为null
。我什么时候会用这样的东西?为什么我们不能只使用function __construct($id, $args) {
。
答案 0 :(得分:4)
那些是default arguments。当调用者未提供它们时,它们将被设置为这些值。否则,它将被设置为调用者的值。
答案 1 :(得分:3)
这样$x = MyClass("12", array(1, 2, 3))
和$y = MyClass()
都有效。
如果没有这些默认参数,MyClass()
会产生错误。
答案 2 :(得分:3)
这些是默认参数值。
这意味着您可以在不传递任何参数的情况下调用构造函数,然后构造函数会将这些值添加到参数中。
因此你可以创建一个这样的实例:
$mc = MyClass();
那么这什么时候有用呢?假设您有一个通常具有相同参数的类,假设您有类Door
,通常属于normal
类型。然后你可以省略传递该值,但有时你想要一个类型安全的Door
然后你想传递它。澄清:
class Door {
private $door_type;
public function __construct($type='normal') {
$this->door_type = $type;
}
}
//Create a 'normal' door
$normal_door = new Door();
$normal_door = new Door('normal'); //the same as above
//Create a 'safe' door
$safe_door = new Door('safe');
这个例子显然不是你在现实世界中实现它的方式,但我希望你看到它的使用。
作为一个注释,并非所有语言都支持这一点,例如Java不支持。