Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In C#, there is a new feature coming with 4.0 called Named Arguments and get along well with Optional Parameters.

private static void writeSomething(int a = 1, int b = 2){
   // do something here;
}

static void Main()
{
   writeSomething(b:3); // works pretty well 
}

I was using this option to get some settings value from users.

In PHP, I cannot find anything similar except for the optional parameters but I am accepting doing $.fn.extend (jQuery) kind of function :

function settings($options)
{
   $defaults = array("name"=>"something","lastname"=>"else");
   $settings = array_merge($defaults,$options);
}

settigs(array("lastname"=>"John");

I am wondering what kind of solutions you are using or you would use for the same situation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

As you found out, named arguments don't exist in PHP.


But one possible solution would be to use one array as unique parameter -- as array items can be named :

my_function(array(
    'my_param' => 10, 
    'other_param' => 'hello, world!', 
));


And, in your function, you'd read data from that unique array parameter :

function my_function(array $params) {

    // test if $params['my_param'] is set ; and use it if it is
    // test if $params['other_param'] is set ; and use it if it is
    // test if $params['yet_another_param'] is set ; and use it if it is
    // ...

}


Still, there is one major inconvenient with this idea : looking at your function's definition, people will have no idea what parameters it expects / they can pass.

They will have to go read the documentation each time they want to call your function -- which is not something one loves to do, is it ?

Additionnal note : IDEs won't be able to provide hints either ; and phpdoc will be broken too...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...