list - PHP listing function arguments with initial values -


so know can code function's arguments have default value if not supplied when function called this:

edit: added example of how interface implemented

   interface my_interface {    function my_function();  }  class my_class implements my_interface {    # because interface calls function no options error occur   function my_function($arg_one, $arg_two = 'name') {     ...   }  }   class another_class implements my_interface {    # class have no errors , complies implemented interface   # can have number of arguments passed   function my_function() {      list($arg_one, $arg_two, $arg_three) = func_get_args();      ...    }  }    

however, making functions invoke func_get_args() method instead when using them inside classes can implement functions interface. there way use list() function can assign variables default value or need verbose , ugly way? have right is:

  function my_function() {    list($arg_one, $arg_two) = func_get_args();   if(is_null($arg_two)) $arg_two = 'name';    ...  }  

what like, accomplishes same thing, isn't verbose. maybe this, of course doesn't flag error:

  function my_function() {    # if $arg_two not supplied default value remain unchanged?   # thus, calling next commented line solution?   # $arg_two = 'name';   list($arg_one, $arg_two = 'name') = func_get_args();    ...  }  

i hope intent clear , please feel free ask clarification. know may seem banal or simple question appreciate in advance!

you cannot use default values list language construct. can, however, use 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 example, my_function(0, array()) behaves same my_function('default_one', 'name').


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -