将多个变量传递给使用PHP的函数的最佳实践是什么? [英] What are the best practices for passing multiple variables to a function using PHP

查看:102
本文介绍了将多个变量传递给使用PHP的函数的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要5个参数的函数,随着应用程序的增长,我们需要添加几个参数,最后以9个参数结束,其中4个参数具有默认值。



我更喜欢这样做

  fun(数组(
'par1'=>'x',
'par2'=>'y',
.....


绝迹

  func($ par1,$ par2,$ par3,...); 

您怎么看?

解决方案

高度依赖于用例。



但这里有一些解决方案。






固定订单



如果订单有点固定且您从不需要更改, :

 <?php 

函数fn($ a1,$ a2,$ a3,$ a4,$ a5,$ a6 = null,$ a7 =foo,$ a8 =bar,数组$ a9 = array()){}

优点


  • 自我记录

  • 类型提示

  • 默认值




  • $ b


    • 固定订单






    Array



    另一方面,如果订单有所不同,请使用数组thingy。

     <?php 

    函数fn($ a1,$ a2,$ a3,$ a4,$ a5,array $选项al = array()){}

    fn(,,,,,array(arg9=>假));

    优点


    • 易于使用

    • 没有固定订单



    • 缺点


      • 不自行记录

      • 验证成本高






      • 参数对象



        参数对象当然也是一种有效的解决方案,但是处理起来不切实际:

         <?php 

        class Args {

        public $ arg5 =foo;

        public $ arg6 =bar;

        public $ arg7 = null;

        public $ arg8 = array();

        public $ arg9 = true;


        $ b函数fn($ arg1,$ arg2,$ arg3,$ arg4,$ arg5,\ Args $可选= null){}

        //现在出现不切实际的部分。
        $ optional = new Args();
        $ optional-> arg9 = false;
        fn(,,,,,$ optional);

        优点


        • 自行记录

        • 没有固定订单


          缺点


          • 非常不实际

          • 验证成本高






          数组到参数对象



          两种方法:

           <?php 

          类Args {

          public $ arg5 =foo;

          public $ arg6 =bar;

          public $ arg7 = null;

          public $ arg8 = array();

          public $ arg9 = true;
          $ b $ public __construct($ args){
          foreach($ args as $ property => $ value){
          $ this->set {$ property}( $值);



          public function setArg5($ value){
          if(is_string($ value)=== false){
          throw new \\ \\InvalidArgumentException;
          }
          $ this-> arg5 = $ value;
          }

          //等等...

          }

          函数fn($ arg1,$ arg2,$ arg3, $ arg4,$ arg5,array $ optional = null){
          if(isset($ optional)){
          $ optional = new Args($ optional);

          // ...
          }

          fn(,,,,,array(arg9= > false));

          优点


          • 轻松验证

          • 分离关注

          • 轻松传递

          • 易于处理

          • 可以记录API



          缺点 >


          • 仍然无法将其记录为与固定参数方法一样好

          • 验证代价高昂






          可变因子



          PHP 5.6中有一项新功能,您可能会发现它很有用, variadics

           <?php 

          函数fn($ a1,$ a2,$ a3,$ a4,$ a5,.. 。$ optional){}

          优点


          • 非常快

          • 允许构建特殊的API(例如,数据库准备好的语句绑定) ul>

            缺点





            • 验证费用昂贵






            命名参数



            我们可能会看到命名参数


            I have a function that takes 5 parameters, and as the application grew we needed to add few more parameters which ended up in 9 parameters with 4 of them having default values.

            I was wondering is it better to pass parameters like this or use an array?

            I prefer to have it like this

            fun(array(
                 'par1' => 'x',
                 'par2' => 'y',
                 .....
                )
             )
            

            Insted of

            func($par1, $par2, $par3, ...);
            

            What do you think?

            解决方案

            Highly depends on the use case.

            But here are some solutions to this problem.


            Fixed Order

            If the order is somewhat fixed and you never have a need to change it, then:

            <?php
            
            function fn($a1, $a2, $a3, $a4, $a5, $a6 = null, $a7 = "foo", $a8 = "bar", array $a9 = array()) {}
            

            Pros

            • Self documenting
            • Type hinting
            • Default values

            Cons

            • Fixed order

            Array

            If on the other hand the order is somewhat different all the time, use the array thingy.

            <?php
            
            function fn($a1, $a2, $a3, $a4, $a5, array $optional = array()) {}
            
            fn("", "", "", "", "", array("arg9" => false));
            

            Pros

            • Easy to use
            • No fixed order

            Cons

            • Not self documenting
            • Costly to validate

            Parameter Object

            A parameter object is of course a valid solution as well, but impractical to handle:

            <?php
            
            class Args {
            
              public $arg5 = "foo";
            
              public $arg6 = "bar";
            
              public $arg7 = null;
            
              public $arg8 = array();
            
              public $arg9 = true;
            
            }
            
            function fn($arg1, $arg2, $arg3, $arg4, $arg5, \Args $optional = null) {}
            
            // Now comes the impractical part.
            $optional = new Args();
            $optional->arg9 = false;
            fn("", "", "", "", "", $optional);
            

            Pros

            • Self documenting
            • No fixed order

            Cons

            • Highly impractical
            • Costly to validate

            Array to Parameter Object

            You could mix the two approaches:

            <?php
            
            class Args {
            
              public $arg5 = "foo";
            
              public $arg6 = "bar";
            
              public $arg7 = null;
            
              public $arg8 = array();
            
              public $arg9 = true;
            
              public __construct($args) {
                foreach ($args as $property => $value) {
                  $this->"set{$property}"($value);
                }
              }
            
              public function setArg5($value) {
                if (is_string($value) === false) {
                  throw new \InvalidArgumentException;
                }
                $this->arg5 = $value;
              }
            
              // and so on ...
            
            }
            
            function fn($arg1, $arg2, $arg3, $arg4, $arg5, array $optional = null) {
              if (isset($optional)) {
                $optional = new Args($optional);
              }
              // ...
            }
            
            fn("", "", "", "", "", array("arg9" => false));
            

            Pros

            • Easy validation
            • Separation of concern
            • Easy to pass along
            • Easy to handle
            • Possible to document the API

            Cons

            • Still not possible to document it as good as the fixed args approach
            • Costly to validate

            Variadics

            There's a new feature in PHP 5.6 that you might find useful, variadics:

            <?php
            
            function fn($a1, $a2, $a3, $a4, $a5, ...$optional) {}
            

            Pros

            • Very fast
            • Allows to build special APIs (e.g. database prepared statement binding)

            Cons

            • Not easily documented
            • Costly to validate

            Named Parameters

            And we might see named parameters in the future.

            这篇关于将多个变量传递给使用PHP的函数的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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