Fan
Fan

Reputation: 1180

Call function with different arguments type in php

I need to build a method column which can called with different arguments type, such like the situation here .

         ->column('herald','style')
         ->column('herald','style','styleText')
         ->column('herald',['kind','style'])
         ->column('herald',['kind','style'],['kindText','styleText'])
         ->column('item',['kind','style'],false)
         ->column('item',['kind','style'],['kindText','styleText'],false)
         ->column('herald_style','style',false)
         ->column('herald_style','style','styleText',false)

I just want the function can be called clearly ,to overwrite like the Java do, and I have been tried using the func_get_args() to handle the arguments one by one, but it`s seem worse..
Is that have any way to do ?

Upvotes: 0

Views: 81

Answers (3)

astratyandmitry
astratyandmitry

Reputation: 500

You can use func_get_args() at body of your function like this:

function callMe() {
    dd(func_get_args());
} 

Also if it depends on count of arguments you can use func_num_args()

http://php.net/manual/ru/function.func-get-args.php

Upvotes: 0

Steve
Steve

Reputation: 1963

Accepting a variable number of arguments in a function?

If using PHP 5.6+ you can use the splat operator ... to put any submitted arguments into an array.

function column(...$args) {

   // this is how many arguments were submitted
   $number_of_arguments = count($args);

   // iterate through them if you want...
   foreach($args as $arg) {

      // ...and process the arguments one by one
      do_something_with($arg);
   }
}

See example 13 on http://php.net/manual/en/functions.arguments.php

If using an earlier version of PHP then Sanjay Kumar N S's answer will do it.

Upvotes: 1

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4739

If you mean ['kind','style'] as an array, then try this:

<?php
function column()
{
    $numargs = func_num_args();
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . (!is_array($arg_list[$i]) ? $arg_list[$i]: ' an array ' ). "<br />";
    }
    echo "<br /><br />";
}

column('herald','style');
column('herald','style');
column('herald','style','styleText');
column('herald',array('kind','style'));
column('herald',array('kind','style'),array('kindText','styleText'));
column('item',array('kind','style'),false);
column('item',array('kind','style'),array('kindText','styleText'),false);
column('herald_style','style',false);
column('herald_style','style','styleText',false);

?>

Upvotes: 0

Related Questions