dongzaijiao4863 2018-08-16 03:49
浏览 104
已采纳

声明函数时PHP的参数顺序

This is a curiosity question. When creating a function, is there a recommended way to order the parameters? I mean, if I am going to create a function that receives 3 parameters, lets say int $a, $str b and $mixed $c, is there a reason to pick one order over another? like prefer function f($a, $b, $c) instead of function f($c, $b, $c) based on whatever? like the parameter types or anything else?

I know that optional parameters must always go at the end, but apart of that, is there any standard or practical recommendations that would affect performance or something?

In short, I only want to know if the order of the parameters of the function is always arbitrary or not.

NOTE: my question is about when functions are declared only.

  • 写回答

3条回答 默认 最新

  • doumu5662 2018-08-16 03:56
    关注

    They are relatively arbitrary, however there's a two main methodologies I've seen. The least common is "Order of Use", this only makes sense in sequential functions, where $this comes before $that.

    However the typical way is something along the lines of "most important" or required arguments. You don't want important, optional, optional, optional, optional, optional, important - because then you'll need the optional ones set to '' or null or false in order to define the last important one.

    Something like function test( $data_key, $number_of_results = 5, $classes = '' ){} makes sense because you can call test( 'my_key' ); and get arguably usable results.

    Where if it was function test( $number_of_results = 5, $classes = '', $data_key ){}, you would make the semi-optional arguments before data_key required in a sense that they have to be passed to the function first: test( 5, '', 'my_key' );

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

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法