在PHP中命名的参数 [英] Named Arguments in PHP

查看:91
本文介绍了在PHP中命名的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,有4.0称为命名参数来一个新的功能和可选参数相处得很好。

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.

在PHP中,我找不到除可选参数类似的事情,但我接受这样 $ fn.extend (jQuery的)各种功能:

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.

推荐答案

当你发现,命名的参数不存在PHP

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 ?

其它附加注释:集成开发环境将不能够提供提示任;和PHPDoc的将太破了...

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

这篇关于在PHP中命名的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆