2011-10-28 34 views

回答

4

PHP中沒有枚舉。 只需事先定義你的常量,然後使用它們。 如果你不想把它們定義爲全局常量(你可能不應該在這種情況下),你可以在你的類中定義它們。

class myclass { 
    const ONE = 1; 
    const TWO = 2; 
    const THREE = 3; 

    public function testit() { 

     echo("omid". self::ONE); 
     echo ("omid". self::TWO); 
    } 

} 

如果你不斷嘗試使用不那麼確定你會得到一個錯誤

2

您是在查找define()

define('one',1); 

This answer也有枚舉一個很好的PHP解決方案:

class DaysOfWeek 
{ 
    const Sunday = 0; 
    const Monday = 1; 
    // etc. 
} 

var $today = DaysOfWeek::Sunday; 
1

這是你想要做什麼?

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

沒有枚舉,你可以做的就是這個,如果你需要這個只有一個功能:

function foobar($str, $num){ 
    // allowed values (whitelist) 
    static $num_allowed = array('one', 'two', 'three'); 
    if(!in_array($num, $num_allowed)){ 
    // error 
    } 
    // ... 
} 
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

相關問題