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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大