php - How to inform only the first and the last arguments of a function? -


how may use function , inform first , last arguments?

function

function foo($first = false, $second = false, $third = false, $last = false) {   if($first && $last)   {     echo 'ok';   } } 

i've tried code below, didn't work...

foo($first = true, $last = true); 

php doesn't named arguments python does. see this question more info.

however, life can made easier using other techniques like...

modify signature of function accept arguments associative array

function

function foo($parameters) {   // provide default values if parameters not specified   $first = isset($parameters['first']) ? $parameters['first'] : false;   $second = isset($parameters['second']) ? $parameters['second'] : false;   $third = isset($parameters['third']) ? $parameters['third'] : false;   $last = isset($parameters['last']) ? $parameters['last'] : false;    if($first && $last)   {     echo 'ok';   } } 

call

foo(['first' => true, 'last' => true]); 

this way suitable when have number of parameters big , variative enough , have complex logic inside function writing code pays off.

it not convenient, however, because default values specified not in obvious way, there's code , it's hard track parameter usages.

modify signature of function accept parameter object holds necessary info

this way go complex signatures , if have cascade of methods use same arguments. love because solved big problem passing 10 query parameters through processing pipeline. it's 1 object possibility find every parameter usage , friendly autosuggestion of available parameters when typing ->.

parameter object class

class parameterobject {     public $first = false;     public $second = false;     public $third = false;     public $last = false; } 

function

function foo(parameterobject $paramobj) {   if($paramobj->first && $paramobj->last)   {     echo 'ok';   } } 

call

$paramobj = new parameterobject(); $paramobj->first = true; $paramobj->last = true;  foo($paramobj); 

note! can modify object use method setting parameters provide possibility of chaining if return $this in every set method. function call like this:

$paramobj = new parameterobject(); foo($paramobj->setfirst(true)->setsecond(true)); 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -