Calling functions with multiple arguments in php

I have defined a php function:

function my_function($text = '', $relative = false, $icon = true) {
//do something
}

It works as expected with default values. But when I want to change the value of one variable it doesn’t work:

Read More
my_function($icon = false); // this doesn't change anything

I have to call it with all variables to make changes take effect:

my_function($text = '', $relative = false, $icon = false); // this changes the output

I am working in php 5.4.1 and WordPress. What I do wrong? Thanks.

Related posts

Leave a Reply

4 comments

  1. You must provide values for any default arguments to the left (in function signature) of the argument you want to change.

    So given the function:

    function my_function($text = '', $relative = false, $icon = true) {
    //do something
    }
    

    Here are some examples:

    // $text = "foo", $relative = false, $icon = true
    my_function("foo"); 
    
    // $text = "", $relative = true, $icon = true
    my_function("", true) 
    
    // $text = "", $relative = false, $icon = false
    my_function("", false, false) 
    
  2. my_function($icon = false);
    

    You can’t do that in PHP. Well, you can, but it doesn’t do what you think it does. What this does is:

    1. Sets $icon to false
    2. Passes false as the 1st parameter to my_function

    If you want to change the third parameter, you need to also pass the first two.

    my_function('', false, true);
    

    Note: I think it’s python that lets you call functions like that, to set only the Xth parameter.

  3. Nothing wrong, that’s how PHP works.
    And when you’re calling a function, you shouldn’t put variables in the parameter list as you might get undesired results as the variables will be assigned those values. So, this is fine:

    my_function('', false, false);
    

    or:

    my_function($text, $relative, $icon);
    

    or anything in between, no need to assign values.

  4. You may use below code:

    <?php
    
    function my_function($arg = array("text"=>'Default',"relative"=>false,"icon"=>false))
    {
      extract($arg);
          $text = isset($text)?$text:"";
          $relative = isset($relative)? $relative : false;
          $icon = isset($icon)? $icon : false;
    
          //do something
    
    }
    
    my_function(array("icon"=>true));
    
    ?>
    

    WARNING: if you use this way. you should initialise the variable or check the if it is exists.