Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, how to pass func-get-args values to another function as list of arguments?

Tags:

php

I want to create a function (my_function()) getting unlimited number of arguments and passing it into another function (call_another_function()).

function my_function() {        another_function($arg1, $arg2, $arg3 ... $argN);     } 

So, want to call my_function(1,2,3,4,5) and get calling another_function(1,2,3,4,5)

I know that I shoud use func_get_args() to get all function arguments as array, but I don't know how to pass this arguments to another function.

Thank you.

like image 711
Kirzilla Avatar asked Jan 24 '10 11:01

Kirzilla


People also ask

How do you get the number of arguments passed to a PHP function?

To get the number of arguments that were passed into your function, call func_num_args() and read its return value. To get the value of an individual parameter, use func_get_arg() and pass in the parameter number you want to retrieve to have its value returned back to you.

Can we pass array as argument in PHP?

You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside. function sendemail($id, $userid){ // ... } sendemail(array('a', 'b', 'c'), 10);

What do you use to separate multiple arguments that are passed to a function in PHP?

Separate parameters by a comma ( , ). Since PHP 8.0, the parameter list can have the trailing comma ( , ) which the PHP interpreter ignores. By default, arguments are passed by value in PHP. Prepend parameters by an ampersand ( & ) to pass arguments by reference.


1 Answers

Try call_user_func_array:

function my_function() {         $args = func_get_args();     call_user_func_array("another_function", $args); } 

In programming and computer science, this is called an apply function.

like image 138
Brian McKenna Avatar answered Oct 14 '22 07:10

Brian McKenna