我有2例。
name
和age
。name
和gender
。我该怎么做?
class User {
function __construct($name=NULL, $gender=NULL, $age=NULL) {
...
}
}
// How do I pass specific arguments here?
$case_1 = new User("Bob", 34);
$case_2 = new User("James", "m");
答案 0 :(得分:2)
您可以在PHP中具有可选参数,但不能具有/或参数,因为这将需要函数重载,而PHP不支持此功能。以您的示例为例,您必须按如下所示调用构造函数:
// How do I pass specific arguments here?
$case_1 = new User("Bob", null, 34);
$case_2 = new User("James", "m");
如果要消除可选参数但必须为null参数,则需要变得聪明。
选项一:使用工厂。对于每个唯一参数,这将需要一个公共参数构造函数以及mutator方法。
class UserFactory {
public static function createWithGender($name, $gender)
{
$user = new User($name);
$user->setGender($gender);
return $user;
}
public static function createWithAge($name, $age)
{
$user = new User($name);
$user->setAge($age);
return $user;
}
}
$case_1 = UserFactory::createWithAge("Bob", 34);
$case_2 = UserFactory::createWithGender("James", "m");
工厂不需要是一个单独的类,您可以根据需要将静态初始化器添加到User类。
class User {
function __construct($name = null)
{
...
}
public static function createWithGender($name, $gender)
{
$user = new static($name);
$user->setGender($gender);
return $user;
}
public static function createWithAge($name, $age)
{
$user = new static($name);
$user->setAge($age);
return $user;
}
}
$case_1 = User::createWithAge("Bob", 34);
$case_2 = User::createWithGender("James", "m");
选项二:做一些参数检测。仅当参数均为唯一类型时,此方法才有效。
class User {
public function __construct($name, $second = null) {
if (is_int($second)) {
$this->age = $second;
} else {
$this->gender = $second;
}
}
}
$case_1 = new User("Bob", 34);
$case_2 = new User("James", "m");