我可以有这样的功能吗:
public function user_to(String $user = null){
$this->user = $user;
return $this;
}
还有一个这样的
public function user_to(Array $user = null){
$this->user = $user;
return $this;
}
没有任何问题吗?我的意思是,我希望仅当参数是字符串时调用第一个参数,而当参数是数组时调用第二个参数。
我知道我可以只使用一个函数并执行 gettype()
来知道它是数组还是字符串,但我想要不同的函数
最佳答案
PHP 不允许多个函数同名。因此,您不应该定义一个具有相同名称但不同变量类型的单独函数,而是可以在函数内部检查它。
public function user_to($user = null){
if (is_array($user) || is_string($user)) {
$this->user = $user;
return $this;
} else {
/* Do whatever; for example throw an exception or return false */
}
}
尝试重新声明 PHP 中已存在的函数会产生 fatal error 。从手册来看,
PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.
在即将推出的 PHP 8 中,您可以在类型提示中定义多种类型,或“联合类型”( reference )。
因此,您可以要求参数为数组或字符串,或者可为空(因为这是默认值)。
public function user_to(array|string|null $user = null) {
$this->user = $user;
return $this;
}
但是,如果您插入不同的类型,这将引发 fatal error ,类似于..
Fatal error: Uncaught TypeError: Argument 1 passed to user_to() must be of the type string, object given
关于php - 相同函数名不同参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48268184/