【问题标题】:How to define parameter with constant variables for function in php? [duplicate]如何在php中为函数定义带有常量变量的参数? [复制]
【发布时间】:2011-12-17 07:19:53
【问题描述】:

可能重复:
PHP and Enums

我想创建一个具有多个参数的函数,其中一个具有多个常量变量。 例如:

<?php
function print($str, $num){...}
.
.
.
print("omid",one);
print("omid",two);
?>

在这个例子中 $num 由常量变量组成:"one,two,three" 现在,如何实施呢? php中有枚举吗?

感谢您的宝贵时间

【问题讨论】:

    标签: php


    【解决方案1】:

    我假设您想要枚举类型:

    试试这样的代码

    class DAYS
    {
       private $value;
       private function __construct($value)
       {
          $this->value = $value;
       }
       private function __clone()
       {
          //Empty
       }
       public static function MON() { return new DAYS(1); }
       public static function TUE() { return new DAYS(2); }
       public static function WED() { return new DAYS(3); }
       public function AsInt() { return $this->value; }
    }
    

    我有一个网页可以用来生成此代码:http://well-spun.co.ukcode_templates/enums.php

    【讨论】:

      【解决方案2】:

      没有枚举,如果你只需要一个函数,你可以这样做:

      function foobar($str, $num){
        // allowed values (whitelist)
        static $num_allowed = array('one', 'two', 'three');
        if(!in_array($num, $num_allowed)){
          // error
        }
        // ...
      }
      

      【讨论】:

        【解决方案3】:

        这是你想做的吗?

        $nums = array(1 => 'one', 2 => 'two', 'three');
        echo $nums[1]; // one
        echo $nums[3]; // three
        

        【讨论】:

          【解决方案4】:

          php 中没有枚举。 只需事先定义常量,然后使用它们。 如果您不想将它们定义为全局常量(在这种情况下您可能不应该),您可以在您的类中定义它们。

          class myclass {
              const ONE = 1;
              const TWO = 2;
              const THREE = 3;
          
              public function testit() {
          
                  echo("omid". self::ONE);
                  echo ("omid". self::TWO);
              }
          
          }
          

          如果你尝试使用的常量没有定义,那么你会得到一个错误

          【讨论】:

            【解决方案5】:

            你在找define()吗?

            define('one',1);
            

            This answer 也有一个很好的枚举 PHP 解决方案:

            class DaysOfWeek
            {
                const Sunday = 0;
                const Monday = 1;
                // etc.
            }
            
            var $today = DaysOfWeek::Sunday;
            

            【讨论】:

              猜你喜欢
              • 2012-04-18
              • 1970-01-01
              • 2021-06-26
              • 2012-03-20
              • 2012-06-19
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多