【问题标题】:help with passing arguments to function帮助将参数传递给函数
【发布时间】:2009-12-09 00:43:30
【问题描述】:
function get_tags_by_criteria($gender="%", $min_age_of_birth="%", $max_age_of_birth="%", $country="%", $region="%", $city="%", $tag="") {

当我只想传递标签参数并默认让其他参数时,我该怎么写?

我试过了,但是没用。

    get_tags_by_criteria("", "", "", "", "", "", computer);

【问题讨论】:

    标签: php function tags


    【解决方案1】:

    您可以使用关联数组模拟命名参数:

    function my_function($options)
     {
      extract($options);
     }
    

    然后调用

    my_function(array("parameter1" => "value1", "parameter2" => "value2"));
    

    结合强大的检查和函数内的默认值表,对我来说效果很好。

    缺点:没有 phpDoc 约定来记录参数,并且您的 IDE 将无法在您键入时向您显示可用的参数。您必须将可用参数输入到 @desc 块中,这取决于您的 IDE,可能看起来不错,也可能不好看。

    一种解决方法是在函数中声明所有参数,但将除第一个参数之外的所有参数设为可选。然后第一个可以是包含值的关联数组。

    【讨论】:

    【解决方案2】:

    把标签参数放在第一位:

    function get_tags_by_criteria($tag="", $gender="%", $min_age_of_birth="%", $max_age_of_birth="%", $country="%", $region="%", $city="%") 
    

    然后这样称呼它:

    get_tags_by_criteria(computer);
    

    【讨论】:

      【解决方案3】:

      PHP 中没有命名参数传递。通常,如果您有超过 4 个参数并且其中很多是可选的,您可能需要考虑使用数组或对象:

      function get_tags_by_criteria($args) {
        ...
      }
      
      get_tags_by_criteria(array('gender' => 'M', 'tag' => 'php'));
      

      您可以改为使用对象显式设置允许的参数。

      【讨论】:

        【解决方案4】:

        很遗憾,您不能这样做 - 未指定的可选参数必须始终位于函数参数列表的末尾。相反,您可以做的是将 NULL 用于您不想指定的参数,然后让您的函数检查参数是否为 NULL 并为其分配默认值。

        【讨论】:

        • 不错的答案,null 或任何其他值。
        • 任何随机值都可以工作,是的,但我更喜欢 NULL,因为它不太可能与您可能想要传递的任何实际非默认值重叠。 :)
        【解决方案5】:

        这在 PHP 中是不可能的。

        【讨论】:

        • 我应该怎么做才能获得相同的效果来选择要传递的参数以及我想使用默认值的参数?我不想为此创建 7 个不同的函数。
        • 很抱歉,创建 7 个不同的函数是唯一的选择,不过 OOP 可能会帮助您。
        【解决方案6】:

        CakePHP 框架经常使用关联数组来指定一组选项。它甚至可以让您指定单个参数或关联数组。以模型类上的find methods为例。

        这是我试图让您的功能更灵活的尝试:

        <?php
        function get_tags_by_criteria(
            $gender = '%', 
            $min_age_of_birth = '%', 
            $max_age_of_birth = '%', 
            $country = '%', 
            $region = '%', 
            $city = '%', 
            $tag = '') 
        {
            if (is_array($gender))
            {
                $options = $gender;
                $gender = '%'; // reset to default
                extract($options);
            }
        
            $msg = "gender=$gender, min_age=$min_age_of_birth, " .
                "max_age=$max_age_of_birth, country=$country, region=$region, " .
                "city=$city, tag=$tag";
            return $msg;
        }
        ?>
        <p><?php echo get_tags_by_criteria('M'); ?></p>
        <p><?php echo get_tags_by_criteria('M', 10); ?></p>
        <p><?php echo get_tags_by_criteria(array(
            'country' => 'ca', 
            'tag' => 'sample')); ?></p>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-16
          • 1970-01-01
          • 2013-01-27
          • 2021-04-18
          相关资源
          最近更新 更多