dongzaijiao4863 2018-08-15 19: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-15 19: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部