Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

c# - Named Arguments in PHP

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

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

1 Reply

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...