PHP函数重载 [英] PHP function overloading

查看:23
本文介绍了PHP函数重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 C++ 背景 ;)
如何重载 PHP 函数?

Coming from C++ background ;)
How can I overload PHP functions?

如果有任何参数,一个函数定义,如果没有参数另一个?在 PHP 中可能吗?或者我应该使用 if else 来检查是否有任何从 $_GET 和 POST 传递的参数??并将它们联系起来?

One function definition if there are any arguments, and another if there are no arguments? Is it possible in PHP? Or should I use if else to check if there are any parameters passed from $_GET and POST?? and relate them?

推荐答案

您不能重载 PHP 函数.函数签名仅基于它们的名称,不包括参数列表,因此不能有两个具有相同名称的函数.类 方法重载 在 PHP 中与在许多其他语言中不同.PHP 使用相同的词,但它描述了不同的模式.

You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. Class method overloading is different in PHP than in many other languages. PHP uses the same word but it describes a different pattern.

但是,您可以声明一个可变参数函数,它接受可变数量的参数.您将使用 func_num_args()func_get_arg() 得到传递的参数,并正常使用它们.

You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args() and func_get_arg() to get the arguments passed, and use them normally.

例如:

function myFunc() {
    for ($i = 0; $i < func_num_args(); $i++) {
        printf("Argument %d: %s\n", $i, func_get_arg($i));
    }
}

/*
Argument 0: a
Argument 1: 2
Argument 2: 3.5
*/
myFunc('a', 2, 3.5);

这篇关于PHP函数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆