如何在php中为函数定义具有常量变量的参数


How to define parameter with constant variables for function in php?

可能重复:
PHP和枚举

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

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

在本例中,$num由常量变量组成:"一、二、三"现在,如何实现它?php中有Enum吗?

感谢您的时间

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

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

如果您试图使用的常量没有定义,那么您将得到一个错误

你在找define()吗?

define('one',1);

这个答案还有一个很好的枚举PHP解决方案:

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

这就是您想要做的吗?

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

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

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

我假设您想要枚举类型:

尝试一些类似的代码

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