PHP - 使用多个变量调用函数 [英] PHP - Calling functions with multiple variables

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

问题描述



让我们假设一个基本函数:

 函数basicFunction($ var1,$ var2 = 1,$ var3 = 2,$ var4 = 5)
{
// Do一些东西
//返回
}

现在让我们假设我想打电话给该函数具有以下变量:

  $ var1 = 0 

$ var2 = 1

$ var3 = 2

$ var4 = 3

我可以这样做:

  $ someResult = basicFunction(0,1,2,3); 

$ var2 $ var3 已经设置,所以我怎样才能调用函数而不必重复 $ var2 $ var3 ?

解决方案

PHP不支持重载。因此,如果不将它们移动到参数列表的右侧,则无法以任何方式跳过它们。



常见的解决方案是设置默认值与预期不同的类型(即NULL)。然后在函数中设置实际的默认值。这种方法不是很干净,需要一些额外的代码,但如果情况需要,你可以这样做:

  function basicFunction($ var1,$ var2 = NULL,$ var3 = NULL,$ var4 = NULL){
if($ var2 === NULL){
$ var2 = 1;
}

// ...


This seems a basic question I know but I've not been able to find the answer.

Let's assume a basic function:

function basicFunction ( $var1, $var2 = 1, $var3 = 2, $var4 = 5 )
{
// Do some stuff
// Return
}

Now let's assume I want to call that function with the following variables:

$var1 = 0

$var2 = 1

$var3 = 2

$var4 = 3

I can do this:

$someResult = basicFunction( 0, 1, 2, 3 );

$var2 and $var3 are already set though, so how would I call the function without having to repeat the value for $var2 and $var3?

解决方案

PHP does not support overloading. Therefore, you cannot skip them in any way if you don't move them to the very right of the list of arguments.

A common solution is to set a default value of a different type than expected (i.e. NULL). The actual default value is then set within the function. This approach is not really clean and takes some extra lines of code, but if the situation requires it, you can go with this:

function basicFunction($var1, $var2 = NULL, $var3 = NULL, $var4 = NULL) {
    if ($var2 === NULL) {
        $var2 = 1;
    }

    // ...

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

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