dsjlqkbpn029473708 2015-02-21 17:08
浏览 11
已采纳

在php中读取函数参数的最佳方法是什么?

In the past few years I've used this formula to read parameters in my methods inside my php classes:

$params = func_get_args();
if(is_array($params[0])){
    foreach($params[0] as $key => $value){
        ${$key} = $value;
    }
}

And it works fine, as if I pass something like this:

$class->foo(array('bar' => 'hello', 'planet' => 'world'));

I will have in my foo method the variables bar and planet with their relative values. But what I'm asking is: Is there any better way to do it? Something that maybe I can encapsulate in another method for example?

UPDATE

So, taking in consideration rizier123 comment, and after a chat with a friend of mine, I nailed down what I think is the better way pass parameters to function. As I know that I will always pass just one parameter to the function, which is always going to be an array, there's no need to call the func_get_args() function, but I better to expect an array all the time and by default I set an empty array, like in the following example:

class MyClass{
    public function MyMethod(array $options = array()){            
        extract($options);             
    }
}

$my = new MyClass();
$my->MyMethod(array('name' => 'john', 'surname' => 'doe'));
// Now MyMethod has two internal vars called $name and $surname
  • 写回答

3条回答 默认 最新

  • duanchigeng4313 2015-02-21 17:11
    关注

    Yes you can use extract() to convert your arrays to variables, like this:

    extract($params[0]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制