Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass all arguments to another function

Tags:

syntax

php

I have two functions like this:

function mysql_safe_query($format) {
    $args = array_slice(func_get_args(),1);
    $args = array_map('mysql_safe_string',$args);
    $query = vsprintf($format,$args);
    $result = mysql_query($query);
    if($result === false) echo '<div class="mysql-error">',mysql_error(),'<br/>',$query,'</div>';
    return $result;
}

function mysql_row_exists() {
    $result = mysql_safe_query(func_get_args());
    return mysql_num_rows($result) > 0;
}

The problem is that the second function won't work because it passes the args to the first one as an array, when it expects them as different parameters. Is there any way to get around this, preferably without modifying mysql_safe_query?

like image 245
mpen Avatar asked Jun 01 '09 18:06

mpen


People also ask

How do you pass all arguments to a function?

Within any function, you can use the arguments variable to get an array-like list of all of the arguments passed into the function. You don't need to define it ahead of time. It's a native JavaScript object. You can access specific arguments by calling their index.

How do you pass an argument to another function in Python?

Built-in function Like the user-defined functions, we can also pass the built-in function as an argument to another function in Python. Here we will pass the str() function to the map() function along with a Python tuple of strings and numbers. This will return an iterator object which we will to the str.

How do you assign a all the arguments to a single variable?

Assigning the arguments to a regular variable (as in args="$@" ) mashes all the arguments together like "$*" does. If you want to store the arguments in a variable, use an array with args=("$@") (the parentheses make it an array), and then reference them as e.g. "${args[0]}" etc.

How many arguments can be passed to a Python function?

While a function can only have one argument of variable length of each type, we can combine both types of functions in one argument. If we do, we must ensure that positional arguments come before named arguments and that fixed arguments come before those of variable length.


2 Answers

How about using:

$args = func_get_args();
call_user_func_array('mysql_safe_query', $args);
like image 76
John Fiala Avatar answered Oct 16 '22 12:10

John Fiala


N.B. In PHP 5.6 you can now do this:

function mysql_row_exists(...$args) {
    $result = mysql_safe_query(...$args);
    return mysql_num_rows($result) > 0;
}

Also, for future readers, mysql_* is deprecated -- don't use those functions.

like image 29
mpen Avatar answered Oct 16 '22 10:10

mpen