php - 相同函数名不同参数类型

标签 php

我可以有这样的功能吗:

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/

相关文章:

php - Slim 3 多个路由到一个功能?

php - Directadmin + Nginx + php fpm + 位置 : File not found

php - 需要一些帮助在 mysql 中交换两个列值

php - 从 $_SERVER ['PATH_INFO' 分析路径的正确方法]

php 按值对数组进行排序,对于相等的值,按键排序

php - 处理 json_encode 中的特殊字符

php - Mysql Join Query 多次给出相同的结果

php - mysql 中 mysql_insert_id 的替代方案?

php - 列出以前删除的重新创建的专辑名称

php - 甜蜜警报(我想更新数据库状态(默认 :pending) into confirm when i click sweet alert confirm button