1

So I know that you can code for a function's arguments to have a default value if it is not supplied when the function is called like this:

I added an example of how the interface could be implemented:

interface my_interface {

  function my_function();

}

class my_class implements my_interface {

  # because the interface calls for a function with no options an error would occur
  function my_function($arg_one, $arg_two = 'name') {
    ...
  }

}


class another_class implements my_interface {

  # this class would have no errors and complies to the implemented interface
  # it also can have any number of arguments passed to it
  function my_function() {

    list($arg_one, $arg_two, $arg_three) = func_get_args();

    ...

  }

}

However, I like making my functions invoke the func_get_args() method instead so that when using them inside classes I can implement functions from an interface. Is there a way to use the list() function so that I can assign variables a default value or do I need to do it the verbose and ugly way? What I have right now is:

function my_function() {

  list($arg_one, $arg_two) = func_get_args();
  if(is_null($arg_two)) $arg_two = 'name';

  ...

}

What I would like, is something that accomplishes the same thing, but isn't so verbose. Maybe something like this, but of course doesn't flag an error:

function my_function() {

  # If $arg_two is not supplied would its default value remain unchanged?
  # Thus, would calling the next commented line would be my solution?
  # $arg_two = 'name';
  list($arg_one, $arg_two = 'name') = func_get_args();

  ...

}
2
  • I'm not sure why you're doing this, what do you mean by "so that when using them inside classes I can implement functions from an interface?". Could you illustrate why does it matter? Commented Jul 22, 2013 at 0:13
  • i made edits to make the understanding a little better @elclanrs Commented Jul 22, 2013 at 20:53

1 Answer 1

3

You cannot use default values with the list language construct. You can, however, use the modified ternary operator available since PHP 5.3:

function my_function() {
  $arg_one = func_get_arg(0) ?: 'default_one';
  $arg_two = func_get_arg(1) ?: 'name';
  // ...
}

However, beware of implicit type conversions. In my example, my_function(0, array()) behaves the same as my_function('default_one', 'name').

Sign up to request clarification or add additional context in comments.

1 Comment

oh that's clever and looks nice. bummer I can't modify the list function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.