php PHP中具有多个参数的同名函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2147614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Same named function with multiple arguments in PHP
提问by Josh K
I started off OOP with Java, and now I'm getting pretty heavy into PHP. Is it possible to create multiples of a function with different arguments like in Java? Or will the interpreted / untyped nature of the language prevent this and cause conflicts?
我开始使用 Java 进行 OOP,现在我对 PHP 越来越感兴趣。是否可以像在 Java 中一样创建多个具有不同参数的函数?或者语言的解释性/非类型化性质会阻止这种情况并导致冲突吗?
回答by Poindexter
Everyone else has answers with good code explanations. Here is an explanation in more high level terms: Java supports Method overloadingwhich is what you are referring to when you talk about function with the same name but different arguments. Since PHP is a dynamically typed language, this is not possible. Instead PHP supports Default argumentswhich you can use to get much the same effect.
其他人都有很好的代码解释的答案。这是更高级的解释:Java 支持方法重载,这就是您在谈论具有相同名称但不同参数的函数时所指的内容。由于 PHP 是一种动态类型语言,因此这是不可能的。相反,PHP 支持默认参数,您可以使用它来获得相同的效果。
回答by Felix Kling
If you are dealing with classes you can overload methods with __call()(see Overloading) e.g.:
如果您正在处理类,您可以使用__call()(参见Overloading)重载方法,例如:
class Foo {
public function doSomethingWith2Parameters($a, $b) {
}
public function doSomethingWith3Parameters($a, $b, $c) {
}
public function __call($method, $arguments) {
if($method == 'doSomething') {
if(count($arguments) == 2) {
return call_user_func_array(array($this,'doSomethingWith2Parameters'), $arguments);
}
else if(count($arguments) == 3) {
return call_user_func_array(array($this,'doSomethingWith3Parameters'), $arguments);
}
}
}
}
Then you can do:
然后你可以这样做:
$foo = new Foo();
$foo->doSomething(1,2); // calls $foo->doSomethingWith2Parameters(1,2)
$foo->doSomething(1,2,3); // calls $foo->doSomethingWith3Parameters(1,2,3)
This might not be the best example but __callcan be very handy sometimes. Basically you can use it to catch method calls on objects where this method does not exist.
这可能不是最好的例子,但__call有时可能非常方便。基本上,您可以使用它来捕获不存在此方法的对象上的方法调用。
But it is not the same or as easy as in Java.
但这并不像在 Java 中一样或那么容易。
回答by John Conde
Short answer: No. There can only be one function with a given name.
简短回答:不可以。给定名称只能有一个函数。
Longer answer: You can do this by creating a convoluted include system that includes the function with the right number of arguments. Or, better yet, you can take advantage of PHP allowing default values for parameters and also a variable amount of parameters.
更长的答案:您可以通过创建一个复杂的包含系统来实现这一点,该系统包含具有正确数量参数的函数。或者,更好的是,您可以利用 PHP 允许参数的默认值以及可变数量的参数。
To take advantage of default values just assign a value to a parameter when defining the function:
要利用默认值,只需在定义函数时为参数赋值:
function do_something($param1, $param2, $param3 = 'defaultvaule') {}
It's common practice to put parameters with default values at the end of the function declaration since they may be omitted when the function is called and makes the syntax for using them clearer:
通常的做法是将具有默认值的参数放在函数声明的末尾,因为在调用函数时它们可能会被省略,并使使用它们的语法更清晰:
do_something('value1', 'value2'); // $param3 is 'defaultvaule' by default
You can also send a variable amount of parameters by using func_num_args()and func_get_arg()to get the arguments:
您还可以通过使用func_num_args()和func_get_arg()获取参数来发送可变数量的参数:
<?php
function dynamic_args() {
echo "Number of arguments: " . func_num_args() . "<br />";
for($i = 0 ; $i < func_num_args(); $i++) {
echo "Argument $i = " . func_get_arg($i) . "<br />";
}
}
dynamic_args("a", "b", "c", "d", "e");
?>
回答by YOU
Following isn't possible with php
使用 php 无法执行以下操作
function funcX($a){
echo $a;
}
function funcX($a,$b){
echo $a.$b;
}
Instead do this way
而是这样做
function funcX($a,$b=2){
echo $a.$b;
}
funcX(1)will display 12, func(1,3)will display 13
funcX(1)会显示12,func(1,3)会显示13
回答by broox
Like everyone else said, it's not supported by default. Felix's example using __call()is probably the best way.
就像其他人所说的那样,默认情况下不支持它。Felix 的例子使用__call()可能是最好的方法。
Otherwise, if you are using classes that inherit from each other you can always overload the method names in your child classes. This also allows you to call the parent method.
否则,如果您使用的是相互继承的类,您总是可以重载子类中的方法名称。这也允许您调用父方法。
Take these classes for example...
以这些类为例...
class Account {
public function load($key,$type) {
print("Loading $type Account: $key\n");
}
}
class TwitterAccount extends Account {
public $type = 'Twitter';
public function load($key) {
parent::load($key,$this->type);
}
}
Then you can call them like so...
然后你可以这样称呼他们...
$account = new Account();
$account->load(123,'Facebook');
$twitterAccount = new TwitterAccount();
$twitterAccount->load(123);
And your result would be...
你的结果将是......
Loading Facebook Account: 123 Loading Twitter Account: 123
回答by Thirler
No this isn't possible, because PHP cannot infer from the arguments which function you want (you don't specify which types you expect). You can, however, give default values to arguments in php.
不,这是不可能的,因为 PHP 无法从参数中推断出您想要的函数(您没有指定您期望的类型)。但是,您可以为 php 中的参数提供默认值。
That way the caller can give different amounts of arguments. This will call the same function though.
这样调用者就可以给出不同数量的参数。虽然这将调用相同的函数。
Example is:
例子是:
function test($a = true)
This gives a default of true if 0 arguments are given, and takes the calling value if 1 argument is given.
如果给出 0 个参数,则默认值为 true,如果给出 1 个参数,则采用调用值。
回答by Jacob Christensen
I know it's a bit old issue, but since php56 you can:
我知道这是一个老问题,但从 php56 开始,你可以:
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
回答by Ian
I had the idea of something like:
我有这样的想法:
function process( $param1 , $type='array' ) { switch($type) { case 'array': // do something with it break; case 'associative_array': // do something with it break; case 'int_array': // do something with it break; case 'string': // do something with it break; // etc etc... } }
function process( $param1 , $type='array' ) { switch($type) { case 'array': // 用它做点什么 break; case 'associative_array': // 用它做点什么 break; case 'int_array': // 用它做点什么 break; case 'string': // 用它做点什么 break; // 等等等等... } }
回答by Don'tDownvoteMe
I have got 2 methods, getArrayWithoutKeywhich will output all the entries of an array without supplying any key value. The second method getArrayWithKeywill output a particular entry from the same array using a key value. Which is why I have used method overloading there.
我有 2 种方法,getArrayWithoutKey它们将输出数组的所有条目,而无需提供任何键值。第二种方法getArrayWithKey将使用键值从同一数组中输出特定条目。这就是我在那里使用方法重载的原因。
class abcClass
{
private $Arr=array('abc'=>'ABC Variable', 'def'=>'Def Variable');
public function setArr($key, $value)
{
$this->Arr[$key]=$value;
}
private function getArrWithKey($key)
{
return $this->Arr[$key];
}
private function getArrWithoutKey()
{
return $this->Arr;
}
//Method Overloading in PHP
public function __call($method, $arguments)
{
if($method=='getArr')
{
if(count($arguments)==0)
{
return $this->getArrWithoutKey();
}
elseif(count($arguments)==1)
{
return $this->getArrWithKey(implode(',' , $arguments));
}
}
}
}
/* Setting and getting values of array-> Arr[] */
$obj->setArr('name', 'Sau');
$obj->setArr('address', 'San Francisco');
$obj->setArr('phone', 7777777777);
echo $obj->getArr('name')."<br>";
print_r( $obj->getArr());
echo "<br>";
回答by Xav
Overloading is not possible in PHP but you can get around it to some extend with default parameter values as explained in other responses.
重载在 PHP 中是不可能的,但您可以使用默认参数值对其进行某种扩展,如其他响应中所述。
The limit to this workaround is when one wants to overload a function/method according to the parameter types. This is not possible in PHP, one need to test the parameter types yourself, or write several functions. The functions min and max are a good example of this : if there is one parameter of array type it returns the min/max of the array, otherwise it returns the min/max of the parameters.
这种变通方法的限制是当人们想要根据参数类型重载函数/方法时。这在PHP中是不可能的,需要自己测试参数类型,或者写几个函数。函数 min 和 max 就是一个很好的例子:如果有一个数组类型的参数,它返回数组的最小值/最大值,否则返回参数的最小值/最大值。

