PHP - 将变量传递给函数而不传递之前询问的变量?

Is it possible to pass a variable to function without passing the variables that come before it in the function definition?

For example, if my function looks like this:

function doThis( $v1, $v2, $v3 )
{
    echo $v1.$v2.$v3;
}

Can I then call the function with only some of those variables, like doThis("v1",null,"v3") or some other way?

Yes, you can do doThis("v1",null,"v3"), if you prepare your function to handle that null argument.

For example your example will work just fine.

Or, if it makes sense you can change the order of the arguments so you can set defaults.

you can use predefined arguments:

function doThis( $v1, $v2 = "hello", $v3 = 1 ) {}

call to this function only with the first argument, the 2nd and 3rd will be "hello",1 by defualt:

doThis(10);

You can specify default values in the function definition like so:

function doThis($a, $b=null, $c=null) {
    echo $a . $b . $c;
}

doThis("hello", " world"); // yields: hello world

In this function, $a is a required parameter. The other two values are optional.

To appease the commenter below, you can of course still call this function like so:

doThis("hello", null, "world");

and of course, you do not have to provide defaults (but it is a good idea to do so)

+1 on @Alon post

You can also use an array ..

$array['var1'] = null;
$array['var2'] = "foo";
$array['var3'] = "bar";


doThis($array);

function doThis($theArray){
 var_dump($theArray);
}

This way, you can use empty values and N amout of variables.

The answer is: rework your workflow.

I know you don't like that answer, but honestly, if you are passing more than 3 parameters or if sometimes you don't want to pass part of the beginning parameters, you probably want to rethink what you're doing. Function and method calls should be simple. You are probably doing too much in your function.

General tips:

  • Use classes if appropriate. This way you can avoid passing some information around because it's stored in the class and your methods have access to it.
  • Keep methods cohesive. That means your methods and functions should do one thing and do it well.
  • Put variables you want to pass only sometimes at the back. This allows you to simply not pass them if they have $var=null after it. You then check to see if $var===null before doing something with it.

Much cleaner way is passing an array of variables, as demonstrated by @jflaflamme.

Another way is allowing an arbitrary number of variables like this:

function foo()
{
    $arguments = func_get_args();

    if(sizeof($arguments))
    {
        echo implode('', $arguments);
    }
}

foo(1, 2, 3, $some_var);

You can also loop trough the array you obtain via func_get_args, check them for their type (if it's a null, array, object - you name it) and then handle them in a way you deem appropriate.