質問

PHPにはネイティブの列挙がないことを知っています。しかし、私はJavaの世界からそれらに慣れてきました。 IDEの自動補完機能が理解できる定義済みの値を提供する方法として列挙型を使用したいと思います。

定数はトリックを実行しますが、名前空間の衝突の問題があり(または実際には原因)、それらはグローバルです。配列には名前空間の問題はありませんが、あまりにも曖昧であり、実行時に上書きされる可能性があり、IDEはキーを自動入力する方法をほとんど(決して)知りません。

よく使用する解決策/回避策はありますか? PHPの連中が列挙型について何か考えや決定をしたかどうかを思い出しますか?

役に立ちましたか?

解決

ユースケースにもよりますが、通常は次のようなシンプルを使用します。

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

$today = DaysOfWeek::Sunday;

ただし、他のユースケースでは、定数と値の検証をさらに必要とする場合があります。リフレクションに関する以下のコメントと、その他のいくつかのメモに基づいて、より広範な範囲をより適切に提供できる拡張例を示します。事例:

abstract class BasicEnum {
    private static $constCacheArray = NULL;

    private static function getConstants() {
        if (self::$constCacheArray == NULL) {
            self::$constCacheArray = [];
        }
        $calledClass = get_called_class();
        if (!array_key_exists($calledClass, self::$constCacheArray)) {
            $reflect = new ReflectionClass($calledClass);
            self::$constCacheArray[$calledClass] = $reflect->getConstants();
        }
        return self::$constCacheArray[$calledClass];
    }

    public static function isValidName($name, $strict = false) {
        $constants = self::getConstants();

        if ($strict) {
            return array_key_exists($name, $constants);
        }

        $keys = array_map('strtolower', array_keys($constants));
        return in_array(strtolower($name), $keys);
    }

    public static function isValidValue($value, $strict = true) {
        $values = array_values(self::getConstants());
        return in_array($value, $values, $strict);
    }
}

BasicEnumを拡張する単純な列挙型クラスを作成することにより、単純な入力検証にメソッドを使用することができます。

abstract class DaysOfWeek extends BasicEnum {
    const Sunday = 0;
    const Monday = 1;
    const Tuesday = 2;
    const Wednesday = 3;
    const Thursday = 4;
    const Friday = 5;
    const Saturday = 6;
}

DaysOfWeek::isValidName('Humpday');                  // false
DaysOfWeek::isValidName('Monday');                   // true
DaysOfWeek::isValidName('monday');                   // true
DaysOfWeek::isValidName('monday', $strict = true);   // false
DaysOfWeek::isValidName(0);                          // false

DaysOfWeek::isValidValue(0);                         // true
DaysOfWeek::isValidValue(5);                         // true
DaysOfWeek::isValidValue(7);                         // false
DaysOfWeek::isValidValue('Friday');                  // false

補足として、データが変更されない静的/ constクラスでリフレクションを少なくとも1回使用するたびに(enumなど)、それらの結果をキャッシュします毎回新しいリフレクションオブジェクトを使用すると、最終的に顕著なパフォーマンスへの影響があるため(リフレクション呼び出し)(複数の列挙型の連想配列に格納されます)。

ほとんどの人が少なくとも5.3に finally にアップグレードし、 SplEnum が利用可能になりました。これは確かに実行可能なオプションです。コードベース全体に実際の列挙インスタンス化があるという伝統的に直感的でない概念に注意してください。上記の例では、 BasicEnum DaysOfWeek はインスタンス化できません。また、インスタンス化することもできません。

他のヒント

ネイティブ拡張もあります。 SplEnum

  

SplEnumは、列挙オブジェクトをエミュレートおよび作成する機能を提供します   PHPのネイティブ。

http://www.php.net/manual/en/class。 splenum.php

クラス定数はどうですか?

<?php

class YourClass
{
    const SOME_CONSTANT = 1;

    public function echoConstant()
    {
        echo self::SOME_CONSTANT;
    }
}

echo YourClass::SOME_CONSTANT;

$c = new YourClass;
$c->echoConstant();

上記の一番上の答えは素晴らしいです。ただし、2つの異なる方法で extend した場合、どちらの拡張機能が最初に行われた場合でも、関数の呼び出しでキャッシュが作成されます。このキャッシュは、呼び出しが開始された内線に関係なく、その後のすべての呼び出しで使用されます...

これを解決するには、変数と最初の関数を次のように置き換えます。

private static $constCacheArray = null;

private static function getConstants() {
    if (self::$constCacheArray === null) self::$constCacheArray = array();

    $calledClass = get_called_class();
    if (!array_key_exists($calledClass, self::$constCacheArray)) {
        $reflect = new \ReflectionClass($calledClass);
        self::$constCacheArray[$calledClass] = $reflect->getConstants();
    }

    return self::$constCacheArray[$calledClass];
}

class の代わりに interface を使用します:

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

var $today = DaysOfWeek::Sunday;

定数を使用したクラスを使用しました:

class Enum {
    const NAME       = 'aaaa';
    const SOME_VALUE = 'bbbb';
}

print Enum::NAME;

ここで他の回答のいくつかについてコメントしたので、私も自分が重くなると思いました。 結局のところ、PHPは型付き列挙をサポートしていないので、型付き列挙をハックするか、効果的にハッキングするのが非常に難しいという事実に耐えるという2つの方法のいずれかを使用できます。

事実に沿って生活することを好み、代わりにここの他の回答が何らかの方法で使用した const メソッドを使用します。

abstract class Enum
{

    const NONE = null;

    final private function __construct()
    {
        throw new NotSupportedException(); // 
    }

    final private function __clone()
    {
        throw new NotSupportedException();
    }

    final public static function toArray()
    {
        return (new ReflectionClass(static::class))->getConstants();
    }

    final public static function isValid($value)
    {
        return in_array($value, static::toArray());
    }

}

列挙の例:

final class ResponseStatusCode extends Enum
{

    const OK                         = 200;
    const CREATED                    = 201;
    const ACCEPTED                   = 202;
    // ...
    const SERVICE_UNAVAILABLE        = 503;
    const GATEWAY_TIME_OUT           = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;

}

Enum を他のすべての列挙が拡張する基本クラスとして使用すると、 toArray isValid などのヘルパーメソッドが許可されます。 。私にとって、入力された列挙(およびそのインスタンスの管理)は、やっかいすぎます。


仮説

場合 __ getStatic マジックメソッドが存在しました(、できれば __ equals マジックメソッドもあります)これは、一種のマルチトンパターンで軽減できます。

以下は仮説です。機能しません、おそらくいつかは動作します

final class TestEnum
{

    private static 

ここで他の回答のいくつかについてコメントしたので、私も自分が重くなると思いました。 結局のところ、PHPは型付き列挙をサポートしていないので、型付き列挙をハックするか、効果的にハッキングするのが非常に難しいという事実に耐えるという2つの方法のいずれかを使用できます。

事実に沿って生活することを好み、代わりにここの他の回答が何らかの方法で使用した const メソッドを使用します。

abstract class Enum
{

    const NONE = null;

    final private function __construct()
    {
        throw new NotSupportedException(); // 
    }

    final private function __clone()
    {
        throw new NotSupportedException();
    }

    final public static function toArray()
    {
        return (new ReflectionClass(static::class))->getConstants();
    }

    final public static function isValid($value)
    {
        return in_array($value, static::toArray());
    }

}

列挙の例:

final class ResponseStatusCode extends Enum
{

    const OK                         = 200;
    const CREATED                    = 201;
    const ACCEPTED                   = 202;
    // ...
    const SERVICE_UNAVAILABLE        = 503;
    const GATEWAY_TIME_OUT           = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;

}

Enum を他のすべての列挙が拡張する基本クラスとして使用すると、 toArray isValid などのヘルパーメソッドが許可されます。 。私にとって、入力された列挙(およびそのインスタンスの管理)は、やっかいすぎます。


仮説

場合 __ getStatic マジックメソッドが存在しました(、できれば __ equals マジックメソッドもあります)これは、一種のマルチトンパターンで軽減できます。

以下は仮説です。機能しません、おそらくいつかは動作します

<*>values = [ 'FOO' => 1, 'BAR' => 2, 'QUX' => 3, ]; private static

ここで他の回答のいくつかについてコメントしたので、私も自分が重くなると思いました。 結局のところ、PHPは型付き列挙をサポートしていないので、型付き列挙をハックするか、効果的にハッキングするのが非常に難しいという事実に耐えるという2つの方法のいずれかを使用できます。

事実に沿って生活することを好み、代わりにここの他の回答が何らかの方法で使用した const メソッドを使用します。

abstract class Enum
{

    const NONE = null;

    final private function __construct()
    {
        throw new NotSupportedException(); // 
    }

    final private function __clone()
    {
        throw new NotSupportedException();
    }

    final public static function toArray()
    {
        return (new ReflectionClass(static::class))->getConstants();
    }

    final public static function isValid($value)
    {
        return in_array($value, static::toArray());
    }

}

列挙の例:

final class ResponseStatusCode extends Enum
{

    const OK                         = 200;
    const CREATED                    = 201;
    const ACCEPTED                   = 202;
    // ...
    const SERVICE_UNAVAILABLE        = 503;
    const GATEWAY_TIME_OUT           = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;

}

Enum を他のすべての列挙が拡張する基本クラスとして使用すると、 toArray isValid などのヘルパーメソッドが許可されます。 。私にとって、入力された列挙(およびそのインスタンスの管理)は、やっかいすぎます。


仮説

場合 __ getStatic マジックメソッドが存在しました(、できれば __ equals マジックメソッドもあります)これは、一種のマルチトンパターンで軽減できます。

以下は仮説です。機能しません、おそらくいつかは動作します

<*>instances = []; public static function __getStatic($name) { if (isset(static::

ここで他の回答のいくつかについてコメントしたので、私も自分が重くなると思いました。 結局のところ、PHPは型付き列挙をサポートしていないので、型付き列挙をハックするか、効果的にハッキングするのが非常に難しいという事実に耐えるという2つの方法のいずれかを使用できます。

事実に沿って生活することを好み、代わりにここの他の回答が何らかの方法で使用した const メソッドを使用します。

abstract class Enum
{

    const NONE = null;

    final private function __construct()
    {
        throw new NotSupportedException(); // 
    }

    final private function __clone()
    {
        throw new NotSupportedException();
    }

    final public static function toArray()
    {
        return (new ReflectionClass(static::class))->getConstants();
    }

    final public static function isValid($value)
    {
        return in_array($value, static::toArray());
    }

}

列挙の例:

final class ResponseStatusCode extends Enum
{

    const OK                         = 200;
    const CREATED                    = 201;
    const ACCEPTED                   = 202;
    // ...
    const SERVICE_UNAVAILABLE        = 503;
    const GATEWAY_TIME_OUT           = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;

}

Enum を他のすべての列挙が拡張する基本クラスとして使用すると、 toArray isValid などのヘルパーメソッドが許可されます。 。私にとって、入力された列挙(およびそのインスタンスの管理)は、やっかいすぎます。


仮説

場合 __ getStatic マジックメソッドが存在しました(、できれば __ equals マジックメソッドもあります)これは、一種のマルチトンパターンで軽減できます。

以下は仮説です。機能しません、おそらくいつかは動作します

<*>values[$name])) { if (empty(static::

ここで他の回答のいくつかについてコメントしたので、私も自分が重くなると思いました。 結局のところ、PHPは型付き列挙をサポートしていないので、型付き列挙をハックするか、効果的にハッキングするのが非常に難しいという事実に耐えるという2つの方法のいずれかを使用できます。

事実に沿って生活することを好み、代わりにここの他の回答が何らかの方法で使用した const メソッドを使用します。

abstract class Enum
{

    const NONE = null;

    final private function __construct()
    {
        throw new NotSupportedException(); // 
    }

    final private function __clone()
    {
        throw new NotSupportedException();
    }

    final public static function toArray()
    {
        return (new ReflectionClass(static::class))->getConstants();
    }

    final public static function isValid($value)
    {
        return in_array($value, static::toArray());
    }

}

列挙の例:

final class ResponseStatusCode extends Enum
{

    const OK                         = 200;
    const CREATED                    = 201;
    const ACCEPTED                   = 202;
    // ...
    const SERVICE_UNAVAILABLE        = 503;
    const GATEWAY_TIME_OUT           = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;

}

Enum を他のすべての列挙が拡張する基本クラスとして使用すると、 toArray isValid などのヘルパーメソッドが許可されます。 。私にとって、入力された列挙(およびそのインスタンスの管理)は、やっかいすぎます。


仮説

場合 __ getStatic マジックメソッドが存在しました(、できれば __ equals マジックメソッドもあります)これは、一種のマルチトンパターンで軽減できます。

以下は仮説です。機能しません、おそらくいつかは動作します

<*>instances[$name])) { static::

ここで他の回答のいくつかについてコメントしたので、私も自分が重くなると思いました。 結局のところ、PHPは型付き列挙をサポートしていないので、型付き列挙をハックするか、効果的にハッキングするのが非常に難しいという事実に耐えるという2つの方法のいずれかを使用できます。

事実に沿って生活することを好み、代わりにここの他の回答が何らかの方法で使用した const メソッドを使用します。

abstract class Enum
{

    const NONE = null;

    final private function __construct()
    {
        throw new NotSupportedException(); // 
    }

    final private function __clone()
    {
        throw new NotSupportedException();
    }

    final public static function toArray()
    {
        return (new ReflectionClass(static::class))->getConstants();
    }

    final public static function isValid($value)
    {
        return in_array($value, static::toArray());
    }

}

列挙の例:

final class ResponseStatusCode extends Enum
{

    const OK                         = 200;
    const CREATED                    = 201;
    const ACCEPTED                   = 202;
    // ...
    const SERVICE_UNAVAILABLE        = 503;
    const GATEWAY_TIME_OUT           = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;

}

Enum を他のすべての列挙が拡張する基本クラスとして使用すると、 toArray isValid などのヘルパーメソッドが許可されます。 。私にとって、入力された列挙(およびそのインスタンスの管理)は、やっかいすぎます。


仮説

場合 __ getStatic マジックメソッドが存在しました(、できれば __ equals マジックメソッドもあります)これは、一種のマルチトンパターンで軽減できます。

以下は仮説です。機能しません、おそらくいつかは動作します

<*>instances[$name] = new static($name); } return static::

ここで他の回答のいくつかについてコメントしたので、私も自分が重くなると思いました。 結局のところ、PHPは型付き列挙をサポートしていないので、型付き列挙をハックするか、効果的にハッキングするのが非常に難しいという事実に耐えるという2つの方法のいずれかを使用できます。

事実に沿って生活することを好み、代わりにここの他の回答が何らかの方法で使用した const メソッドを使用します。

abstract class Enum
{

    const NONE = null;

    final private function __construct()
    {
        throw new NotSupportedException(); // 
    }

    final private function __clone()
    {
        throw new NotSupportedException();
    }

    final public static function toArray()
    {
        return (new ReflectionClass(static::class))->getConstants();
    }

    final public static function isValid($value)
    {
        return in_array($value, static::toArray());
    }

}

列挙の例:

final class ResponseStatusCode extends Enum
{

    const OK                         = 200;
    const CREATED                    = 201;
    const ACCEPTED                   = 202;
    // ...
    const SERVICE_UNAVAILABLE        = 503;
    const GATEWAY_TIME_OUT           = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;

}

Enum を他のすべての列挙が拡張する基本クラスとして使用すると、 toArray isValid などのヘルパーメソッドが許可されます。 。私にとって、入力された列挙(およびそのインスタンスの管理)は、やっかいすぎます。


仮説

場合 __ getStatic マジックメソッドが存在しました(、できれば __ equals マジックメソッドもあります)これは、一種のマルチトンパターンで軽減できます。

以下は仮説です。機能しません、おそらくいつかは動作します

<*>instances[$name]; } throw new Exception(sprintf('Invalid enumeration value, "%s"', $name)); } private

ここで他の回答のいくつかについてコメントしたので、私も自分が重くなると思いました。 結局のところ、PHPは型付き列挙をサポートしていないので、型付き列挙をハックするか、効果的にハッキングするのが非常に難しいという事実に耐えるという2つの方法のいずれかを使用できます。

事実に沿って生活することを好み、代わりにここの他の回答が何らかの方法で使用した const メソッドを使用します。

abstract class Enum
{

    const NONE = null;

    final private function __construct()
    {
        throw new NotSupportedException(); // 
    }

    final private function __clone()
    {
        throw new NotSupportedException();
    }

    final public static function toArray()
    {
        return (new ReflectionClass(static::class))->getConstants();
    }

    final public static function isValid($value)
    {
        return in_array($value, static::toArray());
    }

}

列挙の例:

final class ResponseStatusCode extends Enum
{

    const OK                         = 200;
    const CREATED                    = 201;
    const ACCEPTED                   = 202;
    // ...
    const SERVICE_UNAVAILABLE        = 503;
    const GATEWAY_TIME_OUT           = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;

}

Enum を他のすべての列挙が拡張する基本クラスとして使用すると、 toArray isValid などのヘルパーメソッドが許可されます。 。私にとって、入力された列挙(およびそのインスタンスの管理)は、やっかいすぎます。


仮説

場合 __ getStatic マジックメソッドが存在しました(、できれば __ equals マジックメソッドもあります)これは、一種のマルチトンパターンで軽減できます。

以下は仮説です。機能しません、おそらくいつかは動作します

<*>value; public function __construct($name) { $this->_value = static::

ここで他の回答のいくつかについてコメントしたので、私も自分が重くなると思いました。 結局のところ、PHPは型付き列挙をサポートしていないので、型付き列挙をハックするか、効果的にハッキングするのが非常に難しいという事実に耐えるという2つの方法のいずれかを使用できます。

事実に沿って生活することを好み、代わりにここの他の回答が何らかの方法で使用した const メソッドを使用します。

abstract class Enum
{

    const NONE = null;

    final private function __construct()
    {
        throw new NotSupportedException(); // 
    }

    final private function __clone()
    {
        throw new NotSupportedException();
    }

    final public static function toArray()
    {
        return (new ReflectionClass(static::class))->getConstants();
    }

    final public static function isValid($value)
    {
        return in_array($value, static::toArray());
    }

}

列挙の例:

final class ResponseStatusCode extends Enum
{

    const OK                         = 200;
    const CREATED                    = 201;
    const ACCEPTED                   = 202;
    // ...
    const SERVICE_UNAVAILABLE        = 503;
    const GATEWAY_TIME_OUT           = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;

}

Enum を他のすべての列挙が拡張する基本クラスとして使用すると、 toArray isValid などのヘルパーメソッドが許可されます。 。私にとって、入力された列挙(およびそのインスタンスの管理)は、やっかいすぎます。


仮説

場合 __ getStatic マジックメソッドが存在しました(、できれば __ equals マジックメソッドもあります)これは、一種のマルチトンパターンで軽減できます。

以下は仮説です。機能しません、おそらくいつかは動作します

<*>values[$name]; } public function __equals($object) { if ($object instanceof static) { return $object->_value === $this->_value; } return $object === $this->_value; } } $foo = TestEnum::$FOO; // object(TestEnum)#1 (1) { // ["_value":"TestEnum":private]=> // int(1) // } $zap = TestEnum::$ZAP; // Uncaught exception 'Exception' with message // 'Invalid enumeration member, "ZAP"' $qux = TestEnum::$QUX; TestEnum::$QUX == $qux; // true 'hello world!' == $qux; // false

まあ、phpのenumのような単純なjavaには、次を使用します。

class SomeTypeName {
    private static $enum = array(1 => "Read", 2 => "Write");

    public function toOrdinal($name) {
        return array_search($name, self::$enum);
    }

    public function toString($ordinal) {
        return self::$enum[$ordinal];
    }
}

そしてそれを呼び出す:

SomeTypeName::toOrdinal("Read");
SomeTypeName::toString(1);

しかし、私はPHP初心者であり、構文に苦労しているため、これは最善の方法ではないかもしれません。 Reflectionを使用して値から定数名を取得するクラス定数をいくつか試しました。

4年後、私はこれに再び出くわしました。私の現在のアプローチは、IDEでのコード補完とタイプセーフを可能にするためです。

基本クラス:

abstract class TypedEnum
{
    private static 

4年後、私はこれに再び出くわしました。私の現在のアプローチは、IDEでのコード補完とタイプセーフを可能にするためです。

基本クラス:

final class DaysOfWeek extends TypedEnum
{
    public static function Sunday() { return self::_create(0); }    
    public static function Monday() { return self::_create(1); }
    public static function Tuesday() { return self::_create(2); }   
    public static function Wednesday() { return self::_create(3); }
    public static function Thursday() { return self::_create(4); }  
    public static function Friday() { return self::_create(5); }
    public static function Saturday() { return self::_create(6); }      
}

列挙の例:

function saveEvent(DaysOfWeek $weekDay, $comment)
{
    // store week day numeric value and comment:
    $myDatabase->save('myeventtable', 
       array('weekday_id' => $weekDay->getValue()),
       array('comment' => $comment));
}

// call the function, note: DaysOfWeek::Monday() returns an object of type DaysOfWeek
saveEvent(DaysOfWeek::Monday(), 'some comment');

使用例:

$monday1 = DaysOfWeek::Monday();
$monday2 = DaysOfWeek::Monday();
$monday1 === $monday2; // true

同じ列挙型エントリのすべてのインスタンスは同じであることに注意してください:

function getGermanWeekDayName(DaysOfWeek $weekDay)
{
    switch ($weekDay)
    {
        case DaysOfWeek::Monday(): return 'Montag';
        case DaysOfWeek::Tuesday(): return 'Dienstag';
        // ...
}

switchステートメント内でも使用できます。

$monday = DaysOfWeek::fromValue(2);
$tuesday = DaysOfWeek::fromName('Tuesday');

名前または値で列挙型エントリを作成することもできます:

$wednesday = DaysOfWeek::Wednesday()
echo $wednesDay->getName(); // Wednesday

または、既存の列挙型エントリから名前(つまり、関数名)を取得できます:

<*>instancedValues; private

4年後、私はこれに再び出くわしました。私の現在のアプローチは、IDEでのコード補完とタイプセーフを可能にするためです。

基本クラス:

<*>

列挙の例:

<*>

使用例:

<*>

同じ列挙型エントリのすべてのインスタンスは同じであることに注意してください:

<*>

switchステートメント内でも使用できます。

<*>

名前または値で列挙型エントリを作成することもできます:

<*>

または、既存の列挙型エントリから名前(つまり、関数名)を取得できます:

<*>value; private

4年後、私はこれに再び出くわしました。私の現在のアプローチは、IDEでのコード補完とタイプセーフを可能にするためです。

基本クラス:

<*>

列挙の例:

<*>

使用例:

<*>

同じ列挙型エントリのすべてのインスタンスは同じであることに注意してください:

<*>

switchステートメント内でも使用できます。

<*>

名前または値で列挙型エントリを作成することもできます:

<*>

または、既存の列挙型エントリから名前(つまり、関数名)を取得できます:

<*>name; private function __construct($value, $name) { $this->_value = $value; $this->_name = $name; } private static function _fromGetter($getter, $value) { $reflectionClass = new ReflectionClass(get_called_class()); $methods = $reflectionClass->getMethods(ReflectionMethod::IS_STATIC | ReflectionMethod::IS_PUBLIC); $className = get_called_class(); foreach($methods as $method) { if ($method->class === $className) { $enumItem = $method->invoke(null); if ($enumItem instanceof $className && $enumItem->$getter() === $value) { return $enumItem; } } } throw new OutOfRangeException(); } protected static function _create($value) { if (self::

4年後、私はこれに再び出くわしました。私の現在のアプローチは、IDEでのコード補完とタイプセーフを可能にするためです。

基本クラス:

<*>

列挙の例:

<*>

使用例:

<*>

同じ列挙型エントリのすべてのインスタンスは同じであることに注意してください:

<*>

switchステートメント内でも使用できます。

<*>

名前または値で列挙型エントリを作成することもできます:

<*>

または、既存の列挙型エントリから名前(つまり、関数名)を取得できます:

<*>instancedValues === null) { self::

4年後、私はこれに再び出くわしました。私の現在のアプローチは、IDEでのコード補完とタイプセーフを可能にするためです。

基本クラス:

<*>

列挙の例:

<*>

使用例:

<*>

同じ列挙型エントリのすべてのインスタンスは同じであることに注意してください:

<*>

switchステートメント内でも使用できます。

<*>

名前または値で列挙型エントリを作成することもできます:

<*>

または、既存の列挙型エントリから名前(つまり、関数名)を取得できます:

<*>instancedValues = array(); } $className = get_called_class(); if (!isset(self::

4年後、私はこれに再び出くわしました。私の現在のアプローチは、IDEでのコード補完とタイプセーフを可能にするためです。

基本クラス:

<*>

列挙の例:

<*>

使用例:

<*>

同じ列挙型エントリのすべてのインスタンスは同じであることに注意してください:

<*>

switchステートメント内でも使用できます。

<*>

名前または値で列挙型エントリを作成することもできます:

<*>

または、既存の列挙型エントリから名前(つまり、関数名)を取得できます:

<*>instancedValues[$className])) { self::

4年後、私はこれに再び出くわしました。私の現在のアプローチは、IDEでのコード補完とタイプセーフを可能にするためです。

基本クラス:

<*>

列挙の例:

<*>

使用例:

<*>

同じ列挙型エントリのすべてのインスタンスは同じであることに注意してください:

<*>

switchステートメント内でも使用できます。

<*>

名前または値で列挙型エントリを作成することもできます:

<*>

または、既存の列挙型エントリから名前(つまり、関数名)を取得できます:

<*>instancedValues[$className] = array(); } if (!isset(self::

4年後、私はこれに再び出くわしました。私の現在のアプローチは、IDEでのコード補完とタイプセーフを可能にするためです。

基本クラス:

<*>

列挙の例:

<*>

使用例:

<*>

同じ列挙型エントリのすべてのインスタンスは同じであることに注意してください:

<*>

switchステートメント内でも使用できます。

<*>

名前または値で列挙型エントリを作成することもできます:

<*>

または、既存の列挙型エントリから名前(つまり、関数名)を取得できます:

<*>instancedValues[$className][$value])) { $debugTrace = debug_backtrace(); $lastCaller = array_shift($debugTrace); while ($lastCaller['class'] !== $className && count($debugTrace) > 0) { $lastCaller = array_shift($debugTrace); } self::

4年後、私はこれに再び出くわしました。私の現在のアプローチは、IDEでのコード補完とタイプセーフを可能にするためです。

基本クラス:

<*>

列挙の例:

<*>

使用例:

<*>

同じ列挙型エントリのすべてのインスタンスは同じであることに注意してください:

<*>

switchステートメント内でも使用できます。

<*>

名前または値で列挙型エントリを作成することもできます:

<*>

または、既存の列挙型エントリから名前(つまり、関数名)を取得できます:

<*>instancedValues[$className][$value] = new static($value, $lastCaller['function']); } return self::

4年後、私はこれに再び出くわしました。私の現在のアプローチは、IDEでのコード補完とタイプセーフを可能にするためです。

基本クラス:

<*>

列挙の例:

<*>

使用例:

<*>

同じ列挙型エントリのすべてのインスタンスは同じであることに注意してください:

<*>

switchステートメント内でも使用できます。

<*>

名前または値で列挙型エントリを作成することもできます:

<*>

または、既存の列挙型エントリから名前(つまり、関数名)を取得できます:

<*>instancedValues[$className][$value]; } public static function fromValue($value) { return self::_fromGetter('getValue', $value); } public static function fromName($value) { return self::_fromGetter('getName', $value); } public function getValue() { return $this->_value; } public function getName() { return $this->_name; } }

列挙の例:

<*>

使用例:

<*>

同じ列挙型エントリのすべてのインスタンスは同じであることに注意してください:

<*>

switchステートメント内でも使用できます。

<*>

名前または値で列挙型エントリを作成することもできます:

<*>

または、既存の列挙型エントリから名前(つまり、関数名)を取得できます:

<*>

グローバルに一意の列挙を使用する必要がある場合(つまり、異なる列挙間で要素を比較する場合でも)、使いやすい場合は、次のコードを使用してください。また、便利だと思う方法をいくつか追加しました。コードの一番上のコメントに例があります。

<?php

/**
 * Class Enum
 * 
 * @author Christopher Fox <christopher.fox@gmx.de>
 *
 * @version 1.0
 *
 * This class provides the function of an enumeration.
 * The values of Enum elements are unique (even between different Enums)
 * as you would expect them to be.
 *
 * Constructing a new Enum:
 * ========================
 *
 * In the following example we construct an enum called "UserState"
 * with the elements "inactive", "active", "banned" and "deleted".
 * 
 * <code>
 * Enum::Create('UserState', 'inactive', 'active', 'banned', 'deleted');
 * </code>
 *
 * Using Enums:
 * ============
 *
 * The following example demonstrates how to compare two Enum elements
 *
 * <code>
 * var_dump(UserState::inactive == UserState::banned); // result: false
 * var_dump(UserState::active == UserState::active); // result: true
 * </code>
 *
 * Special Enum methods:
 * =====================
 *
 * Get the number of elements in an Enum:
 *
 * <code>
 * echo UserState::CountEntries(); // result: 4
 * </code>
 *
 * Get a list with all elements of the Enum:
 *
 * <code>
 * $allUserStates = UserState::GetEntries();
 * </code>
 *
 * Get a name of an element:
 *
 * <code>
 * echo UserState::GetName(UserState::deleted); // result: deleted
 * </code>
 *
 * Get an integer ID for an element (e.g. to store as a value in a database table):
 * This is simply the index of the element (beginning with 1).
 * Note that this ID is only unique for this Enum but now between different Enums.
 *
 * <code>
 * echo UserState::GetDatabaseID(UserState::active); // result: 2
 * </code>
 */
class Enum
{

    /**
     * @var Enum $instance The only instance of Enum (Singleton)
     */
    private static $instance;

    /**
     * @var array $enums    An array of all enums with Enum names as keys
     *          and arrays of element names as values
     */
    private $enums;

    /**
     * Constructs (the only) Enum instance
     */
    private function __construct()
    {
        $this->enums = array();
    }

    /**
     * Constructs a new enum
     *
     * @param string $name The class name for the enum
     * @param mixed 

グローバルに一意の列挙を使用する必要がある場合(つまり、異なる列挙間で要素を比較する場合でも)、使いやすい場合は、次のコードを使用してください。また、便利だと思う方法をいくつか追加しました。コードの一番上のコメントに例があります。

<*> A list of strings to use as names for enum entries */ public static function Create($name,

グローバルに一意の列挙を使用する必要がある場合(つまり、異なる列挙間で要素を比較する場合でも)、使いやすい場合は、次のコードを使用してください。また、便利だと思う方法をいくつか追加しました。コードの一番上のコメントに例があります。

<*>) { // Create (the only) Enum instance if this hasn't happened yet if (self::$instance===null) { self::$instance = new Enum(); } // Fetch the arguments of the function $args = func_get_args(); // Exclude the "name" argument from the array of function arguments, // so only the enum element names remain in the array array_shift($args); self::$instance->add($name, $args); } /** * Creates an enumeration if this hasn't happened yet * * @param string $name The class name for the enum * @param array $fields The names of the enum elements */ private function add($name, $fields) { if (!array_key_exists($name, $this->enums)) { $this->enums[$name] = array(); // Generate the code of the class for this enumeration $classDeclaration = "class " . $name . " {\n" . "private static \$name = '" . $name . "';\n" . $this->getClassConstants($name, $fields) . $this->getFunctionGetEntries($name) . $this->getFunctionCountEntries($name) . $this->getFunctionGetDatabaseID() . $this->getFunctionGetName() . "}"; // Create the class for this enumeration eval($classDeclaration); } } /** * Returns the code of the class constants * for an enumeration. These are the representations * of the elements. * * @param string $name The class name for the enum * @param array $fields The names of the enum elements * * @return string The code of the class constants */ private function getClassConstants($name, $fields) { $constants = ''; foreach ($fields as $field) { // Create a unique ID for the Enum element // This ID is unique because class and variables // names can't contain a semicolon. Therefore we // can use the semicolon as a separator here. $uniqueID = $name . ";" . $field; $constants .= "const " . $field . " = '". $uniqueID . "';\n"; // Store the unique ID array_push($this->enums[$name], $uniqueID); } return $constants; } /** * Returns the code of the function "GetEntries()" * for an enumeration * * @param string $name The class name for the enum * * @return string The code of the function "GetEntries()" */ private function getFunctionGetEntries($name) { $entryList = ''; // Put the unique element IDs in single quotes and // separate them with commas foreach ($this->enums[$name] as $key => $entry) { if ($key > 0) $entryList .= ','; $entryList .= "'" . $entry . "'"; } return "public static function GetEntries() { \n" . " return array(" . $entryList . ");\n" . "}\n"; } /** * Returns the code of the function "CountEntries()" * for an enumeration * * @param string $name The class name for the enum * * @return string The code of the function "CountEntries()" */ private function getFunctionCountEntries($name) { // This function will simply return a constant number (e.g. return 5;) return "public static function CountEntries() { \n" . " return " . count($this->enums[$name]) . ";\n" . "}\n"; } /** * Returns the code of the function "GetDatabaseID()" * for an enumeration * * @return string The code of the function "GetDatabaseID()" */ private function getFunctionGetDatabaseID() { // Check for the index of this element inside of the array // of elements and add +1 return "public static function GetDatabaseID(\$entry) { \n" . "\$key = array_search(\$entry, self::GetEntries());\n" . " return \$key + 1;\n" . "}\n"; } /** * Returns the code of the function "GetName()" * for an enumeration * * @return string The code of the function "GetName()" */ private function getFunctionGetName() { // Remove the class name from the unique ID // and return this value (which is the element name) return "public static function GetName(\$entry) { \n" . "return substr(\$entry, strlen(self::\$name) + 1 , strlen(\$entry));\n" . "}\n"; } } ?>

私もjavaの列挙型が好きなので、このように列挙型を書くのは、Javaの列挙型のように最も似た振る舞いだと思います。 、または抽象クラスですが、コアアイデアは以下のコードに埋め込まれています


class FruitsEnum {

    static $APPLE = null;
    static $ORANGE = null;

    private $value = null;

    public static $map;

    public function __construct($value) {
        $this->value = $value;
    }

    public static function init () {
        self::$APPLE  = new FruitsEnum("Apple");
        self::$ORANGE = new FruitsEnum("Orange");
        //static map to get object by name - example Enum::get("INIT") - returns Enum::$INIT object;
        self::$map = array (
            "Apple" => self::$APPLE,
            "Orange" => self::$ORANGE
        );
    }

    public static function get($element) {
        if($element == null)
            return null;
        return self::$map[$element];
    }

    public function getValue() {
        return $this->value;
    }

    public function equals(FruitsEnum $element) {
        return $element->getValue() == $this->getValue();
    }

    public function __toString () {
        return $this->value;
    }
}
FruitsEnum::init();

var_dump(FruitsEnum::$APPLE->equals(FruitsEnum::$APPLE)); //true
var_dump(FruitsEnum::$APPLE->equals(FruitsEnum::$ORANGE)); //false
var_dump(FruitsEnum::$APPLE instanceof FruitsEnum); //true
var_dump(FruitsEnum::get("Apple")->equals(FruitsEnum::$APPLE)); //true - enum from string
var_dump(FruitsEnum::get("Apple")->equals(FruitsEnum::get("Orange"))); //false

githubでこのライブラリを見つけましたが、答えに代わる非常に適切な代替手段を提供すると思いますこちら。

SplEnumからヒントを得たPHP Enum実装

  • 入力できるヒント: function setAction(Action $ action){
  • メソッド(たとえば、 format parse 、&#8230;)で列挙型を強化できます
  • enumを拡張して新しい値を追加できます(enumを final にして、それを防ぎます)
  • すべての可能な値のリストを取得できます(以下を参照)

宣言

<?php
use MyCLabs\Enum\Enum;

/**
 * Action enum
 */
class Action extends Enum
{
    const VIEW = 'view';
    const EDIT = 'edit';
}

使用法

<?php
$action = new Action(Action::VIEW);

// or
$action = Action::VIEW();

type-hint列挙値:

<?php
function setAction(Action $action) {
    // ...
}

PHPの列挙型で私が見た最も一般的な解決策は、汎用列挙型クラスを作成してから拡張することです。 これをご覧ください。

更新:または、 this が見つかりましたphpclasses.orgから。

これは、PHPでタイプセーフな列挙を処理するためのgithubライブラリです。

このライブラリは、クラスの生成、クラスのキャッシングを処理し、列挙型の組み合わせのために列挙型を処理するためのいくつかのヘルパーメソッド、列挙型の並べ替えのための序数の取得、またはバイナリ値の取得など、タイプセーフな列挙デザインパターンを実装します

生成されたコードは、設定可能なプレーンな古いphpテンプレートファイルを使用するため、独自のテンプレートを提供できます。

phpunitでカバーされる完全なテストです。

githubのphp-enums(気軽にフォーク)

使用法:(@ usage.phpを参照、または詳細については単体テスト)

<?php
//require the library
require_once __DIR__ . '/src/Enum.func.php';

//if you don't have a cache directory, create one
@mkdir(__DIR__ . '/cache');
EnumGenerator::setDefaultCachedClassesDir(__DIR__ . '/cache');

//Class definition is evaluated on the fly:
Enum('FruitsEnum', array('apple' , 'orange' , 'rasberry' , 'bannana'));

//Class definition is cached in the cache directory for later usage:
Enum('CachedFruitsEnum', array('apple' , 'orange' , 'rasberry' , 'bannana'), '\my\company\name\space', true);

echo 'FruitsEnum::APPLE() == FruitsEnum::APPLE(): ';
var_dump(FruitsEnum::APPLE() == FruitsEnum::APPLE()) . "\n";

echo 'FruitsEnum::APPLE() == FruitsEnum::ORANGE(): ';
var_dump(FruitsEnum::APPLE() == FruitsEnum::ORANGE()) . "\n";

echo 'FruitsEnum::APPLE() instanceof Enum: ';
var_dump(FruitsEnum::APPLE() instanceof Enum) . "\n";

echo 'FruitsEnum::APPLE() instanceof FruitsEnum: ';
var_dump(FruitsEnum::APPLE() instanceof FruitsEnum) . "\n";

echo "->getName()\n";
foreach (FruitsEnum::iterator() as $enum)
{
  echo "  " . $enum->getName() . "\n";
}

echo "->getValue()\n";
foreach (FruitsEnum::iterator() as $enum)
{
  echo "  " . $enum->getValue() . "\n";
}

echo "->getOrdinal()\n";
foreach (CachedFruitsEnum::iterator() as $enum)
{
  echo "  " . $enum->getOrdinal() . "\n";
}

echo "->getBinary()\n";
foreach (CachedFruitsEnum::iterator() as $enum)
{
  echo "  " . $enum->getBinary() . "\n";
}

出力:

FruitsEnum::APPLE() == FruitsEnum::APPLE(): bool(true)
FruitsEnum::APPLE() == FruitsEnum::ORANGE(): bool(false)
FruitsEnum::APPLE() instanceof Enum: bool(true)
FruitsEnum::APPLE() instanceof FruitsEnum: bool(true)
->getName()
  APPLE
  ORANGE
  RASBERRY
  BANNANA
->getValue()
  apple
  orange
  rasberry
  bannana
->getValue() when values have been specified
  pig
  dog
  cat
  bird
->getOrdinal()
  1
  2
  3
  4
->getBinary()
  1
  2
  4
  8
abstract class Enumeration
{
    public static function enum() 
    {
        $reflect = new ReflectionClass( get_called_class() );
        return $reflect->getConstants();
    }
}


class Test extends Enumeration
{
    const A = 'a';
    const B = 'b';    
}


foreach (Test::enum() as $key => $value) {
    echo "$key -> $value<br>";
}

それは次のように簡単かもしれません

enum DaysOfWeek {
    Sunday,
    Monday,
    // ...
}

将来的に。

PHP RFC:列挙型

関数パラメータの型安全性、NetBeansでの自動補完、優れたパフォーマンスを実現できるため、以下のアプローチを使用しました。あまり気に入らないのは、クラスを定義した後に [extended class name] :: enumerate(); を呼び出す必要があることです。

abstract class Enum {

    private 

関数パラメータの型安全性、NetBeansでの自動補完、優れたパフォーマンスを実現できるため、以下のアプローチを使用しました。あまり気に入らないのは、クラスを定義した後に [extended class name] :: enumerate(); を呼び出す必要があることです。

<*>value; protected function __construct($value) { $this->_value = $value; } public function __toString() { return (string) $this->_value; } public static function enumerate() { $class = get_called_class(); $ref = new ReflectionClass($class); $statics = $ref->getStaticProperties(); foreach ($statics as $name => $value) { $ref->setStaticPropertyValue($name, new $class($value)); } } } class DaysOfWeek extends Enum { public static $MONDAY = 0; public static $SUNDAY = 1; // etc. } DaysOfWeek::enumerate(); function isMonday(DaysOfWeek $d) { if ($d == DaysOfWeek::$MONDAY) { return true; } else { return false; } } $day = DaysOfWeek::$MONDAY; echo (isMonday($day) ? "bummer it's monday" : "Yay! it's not monday");

以下のEnumクラスの定義は、厳密に入力されており、使用および定義するのに非常に自然です。

定義:

class Fruit extends Enum {
    static public $APPLE = 1;
    static public $ORANGE = 2;
}
Fruit::initialize(); //Can also be called in autoloader

Enumの切り替え

$myFruit = Fruit::$APPLE;

switch ($myFruit) {
    case Fruit::$APPLE  : echo "I like apples\n";  break;
    case Fruit::$ORANGE : echo "I hate oranges\n"; break;
}

>> I like apples

パラメータとしてパス列挙(厳密に入力)

/** Function only accepts Fruit enums as input**/
function echoFruit(Fruit $fruit) {
    echo $fruit->getName().": ".$fruit->getValue()."\n";
}

/** Call function with each Enum value that Fruit has */
foreach (Fruit::getList() as $fruit) {
    echoFruit($fruit);
}

//Call function with Apple enum
echoFruit(Fruit::$APPLE)

//Will produce an error. This solution is strongly typed
echoFruit(2);

>> APPLE: 1
>> ORANGE: 2
>> APPLE: 1
>> Argument 1 passed to echoFruit() must be an instance of Fruit, integer given

Echo Enum as string

echo "I have an $myFruit\n";

>> I have an APPLE

整数で列挙を取得

$myFruit = Fruit::getByValue(2);

echo "Now I have an $myFruit\n";

>> Now I have an ORANGE

名前で列挙を取得

$myFruit = Fruit::getByName("APPLE");

echo "But I definitely prefer an $myFruit\n\n";

>> But I definitely prefer an APPLE

Enumクラス:

/**
 * @author Torge Kummerow
 */
class Enum {

    /**
     * Holds the values for each type of Enum
     */
    static private $list = array();

    /**
     * Initializes the enum values by replacing the number with an instance of itself
     * using reflection
     */
    static public function initialize() {
        $className = get_called_class();
        $class = new ReflectionClass($className);
        $staticProperties = $class->getStaticProperties();

        self::$list[$className] = array();

        foreach ($staticProperties as $propertyName => &$value) {
            if ($propertyName == 'list')
                continue;

            $enum = new $className($propertyName, $value);
            $class->setStaticPropertyValue($propertyName, $enum);
            self::$list[$className][$propertyName] = $enum;
        } unset($value);
    }


    /**
     * Gets the enum for the given value
     *
     * @param integer $value
     * @throws Exception
     *
     * @return Enum
     */
    static public function getByValue($value) {
        $className = get_called_class();
        foreach (self::$list[$className] as $propertyName=>&$enum) {
            /* @var $enum Enum */
            if ($enum->value == $value)
                return $enum;
        } unset($enum);

        throw new Exception("No such enum with value=$value of type ".get_called_class());
    }

    /**
     * Gets the enum for the given name
     *
     * @param string $name
     * @throws Exception
     *
     * @return Enum
     */
    static public function getByName($name) {
        $className = get_called_class();
        if (array_key_exists($name, static::$list[$className]))
            return self::$list[$className][$name];

        throw new Exception("No such enum ".get_called_class()."::\$name");
    }


    /**
     * Returns the list of all enum variants
     * @return Array of Enum
     */
    static public function getList() {
        $className = get_called_class();
        return self::$list[$className];
    }


    private $name;
    private $value;

    public function __construct($name, $value) {
        $this->name = $name;
        $this->value = $value;
    }

    public function __toString() {
        return $this->name;
    }

    public function getValue() {
        return $this->value;
    }

    public function getName() {
        return $this->name;
    }

}

追加

もちろん、IDEにコメントを追加することもできます

class Fruit extends Enum {

    /**
     * This comment is for autocomplete support in common IDEs
     * @var Fruit A yummy apple
     */
    static public $APPLE = 1;

    /**
     * This comment is for autocomplete support in common IDEs
     * @var Fruit A sour orange
     */
    static public $ORANGE = 2;
}

//This can also go to the autoloader if available.
Fruit::initialize();

これは非常に古いスレッドであることがわかりましたが、これについて考えていたので、人々の考えを知りたいと思いました。

注:これをいじくり回していたところ、 __ call()関数を変更しただけで、実際の enums にさらに近づくことができることに気付きました。 __ call()関数は、すべての未知の関数呼び出しを処理します。 RED_LIGHT、YELLOW_LIGHT、GREEN_LIGHTの3つの enums を作成するとします。これを行うには、次の手順を実行します。

$c->RED_LIGHT();
$c->YELLOW_LIGHT();
$c->GREEN_LIGHT();

一度定義したら、それらを再度呼び出して値を取得するだけです:

echo $c->RED_LIGHT();
echo $c->YELLOW_LIGHT();
echo $c->GREEN_LIGHT();

そして、0、1、2を取得する必要があります。楽しんでください!これもGitHubで公開されています。

更新: __ get() __ set()関数の両方が使用されるようになりました。これらを使用すると、必要な場合を除き、関数を呼び出す必要がなくなります。代わりに、次のように言うことができます。

$c->RED_LIGHT;
$c->YELLOW_LIGHT;
$c->GREEN_LIGHT;

値の作成と取得の両方。変数が最初に定義されていないため、配列内のエントリが作成されていないことを確認する __ get()関数が呼び出されます(値が指定されていないため)。そのため、エントリを作成し、指定された最後の値にone(+1)を加えた値を割り当て、最後の値変数をインクリメントし、TRUEを返します。値を設定した場合:

$c->RED_LIGHT = 85;

__ set()関数が呼び出され、最後の値が新しい値に1を加えた値(+1)に設定されます。したがって、列挙型を実行するためのかなり良い方法があり、その場で作成できます。

<?php
################################################################################
#   Class ENUMS
#
#       Original code by Mark Manning.
#       Copyrighted (c) 2015 by Mark Manning.
#       All rights reserved.
#
#       This set of code is hereby placed into the free software universe
#       via the GNU greater license thus placing it under the Copyleft
#       rules and regulations with the following modifications:
#
#       1. You may use this work in any other work.  Commercial or otherwise.
#       2. You may make as much money as you can with it.
#       3. You owe me nothing except to give me a small blurb somewhere in
#           your program or maybe have pity on me and donate a dollar to
#           sim_sales@paypal.com.  :-)
#
#   Blurb:
#
#       PHP Class Enums by Mark Manning (markem-AT-sim1-DOT-us).
#       Used with permission.
#
#   Notes:
#
#       VIM formatting.  Set tabs to four(4) spaces.
#
################################################################################
class enums
{
    private $enums;
    private $clear_flag;
    private $last_value;

################################################################################
#   __construct(). Construction function.  Optionally pass in your enums.
################################################################################
function __construct()
{
    $this->enums = array();
    $this->clear_flag = false;
    $this->last_value = 0;

    if( func_num_args() > 0 ){
        return $this->put( func_get_args() );
        }

    return true;
}
################################################################################
#   put(). Insert one or more enums.
################################################################################
function put()
{
    $args = func_get_args();
#
#   Did they send us an array of enums?
#   Ex: $c->put( array( "a"=>0, "b"=>1,...) );
#   OR  $c->put( array( "a", "b", "c",... ) );
#
    if( is_array($args[0]) ){
#
#   Add them all in
#
        foreach( $args[0] as $k=>$v ){
#
#   Don't let them change it once it is set.
#   Remove the IF statement if you want to be able to modify the enums.
#
            if( !isset($this->enums[$k]) ){
#
#   If they sent an array of enums like this: "a","b","c",... then we have to
#   change that to be "A"=>#. Where "#" is the current count of the enums.
#
                if( is_numeric($k) ){
                    $this->enums[$v] = $this->last_value++;
                    }
#
#   Else - they sent "a"=>"A", "b"=>"B", "c"=>"C"...
#
                    else {
                        $this->last_value = $v + 1;
                        $this->enums[$k] = $v;
                        }
                }
            }
        }
#
#   Nope!  Did they just sent us one enum?
#
        else {
#
#   Is this just a default declaration?
#   Ex: $c->put( "a" );
#
            if( count($args) < 2 ){
#
#   Again - remove the IF statement if you want to be able to change the enums.
#
                if( !isset($this->enums[$args[0]]) ){
                    $this->enums[$args[0]] = $this->last_value++;
                    }
#
#   No - they sent us a regular enum
#   Ex: $c->put( "a", "This is the first enum" );
#
                    else {
#
#   Again - remove the IF statement if you want to be able to change the enums.
#
                        if( !isset($this->enums[$args[0]]) ){
                            $this->last_value = $args[1] + 1;
                            $this->enums[$args[0]] = $args[1];
                            }
                        }
                }
            }

    return true;
}
################################################################################
#   get(). Get one or more enums.
################################################################################
function get()
{
    $num = func_num_args();
    $args = func_get_args();
#
#   Is this an array of enums request? (ie: $c->get(array("a","b","c"...)) )
#
    if( is_array($args[0]) ){
        $ary = array();
        foreach( $args[0] as $k=>$v ){
            $ary[$v] = $this->enums[$v];
            }

        return $ary;
        }
#
#   Is it just ONE enum they want? (ie: $c->get("a") )
#
        else if( ($num > 0) && ($num < 2) ){
            return $this->enums[$args[0]];
            }
#
#   Is it a list of enums they want? (ie: $c->get( "a", "b", "c"...) )
#
        else if( $num > 1 ){
            $ary = array();
            foreach( $args as $k=>$v ){
                $ary[$v] = $this->enums[$v];
                }

            return $ary;
            }
#
#   They either sent something funky or nothing at all.
#
    return false;
}
################################################################################
#   clear(). Clear out the enum array.
#       Optional.  Set the flag in the __construct function.
#       After all, ENUMS are supposed to be constant.
################################################################################
function clear()
{
    if( $clear_flag ){
        unset( $this->enums );
        $this->enums = array();
        }

    return true;
}
################################################################################
#   __call().  In case someone tries to blow up the class.
################################################################################
function __call( $name, $arguments )
{
    if( isset($this->enums[$name]) ){ return $this->enums[$name]; }
        else if( !isset($this->enums[$name]) && (count($arguments) > 0) ){
            $this->last_value = $arguments[0] + 1;
            $this->enums[$name] = $arguments[0];
            return true;
            }
        else if( !isset($this->enums[$name]) && (count($arguments) < 1) ){
            $this->enums[$name] = $this->last_value++;
            return true;
            }

    return false;
}
################################################################################
#   __get(). Gets the value.
################################################################################
function __get($name)
{
    if( isset($this->enums[$name]) ){ return $this->enums[$name]; }
        else if( !isset($this->enums[$name]) ){
            $this->enums[$name] = $this->last_value++;
            return true;
            }

    return false;
}
################################################################################
#   __set().  Sets the value.
################################################################################
function __set( $name, $value=null )
{
    if( isset($this->enums[$name]) ){ return false; }
        else if( !isset($this->enums[$name]) && !is_null($value) ){
            $this->last_value = $value + 1;
            $this->enums[$name] = $value;
            return true;
            }
        else if( !isset($this->enums[$name]) && is_null($value) ){
            $this->enums[$name] = $this->last_value++;
            return true;
            }

    return false;
}
################################################################################
#   __destruct().  Deconstruct the class.  Remove the list of enums.
################################################################################
function __destruct()
{
    unset( $this->enums );
    $this->enums = null;

    return true;
}

}
#
#   Test code
#
#   $c = new enums();
#   $c->RED_LIGHT(85);
#   $c->YELLOW_LIGHT = 23;
#   $c->GREEN_LIGHT;
#
#   echo $c->RED_LIGHT . "\n";
#   echo $c->YELLOW_LIGHT . "\n";
#   echo $c->GREEN_LIGHT . "\n";

?>

これは古いスレッドですが、ほとんどすべての回避策では列挙型アイテムに値を手動で割り当てる必要があるか、列挙型の配列を渡す必要があるため、実際に列挙型のように見える回避策はありません機能へのキー。そこで、私はこのための独自のソリューションを作成しました。

このソリューションを使用して列挙クラスを作成するには、このEnumクラスを単純に拡張し、多数の静的変数を作成し(初期化する必要はありません)、定義のすぐ下でyourEnumClass :: init()を呼び出します列挙型クラス。

edit:これはphp&gt; = 5.3でのみ機能しますが、おそらく古いバージョンでも機能するように変更できます     

/**
 * A base class for enums. 
 * 
 * This class can be used as a base class for enums. 
 * It can be used to create regular enums (incremental indices), but it can also be used to create binary flag values.
 * To create an enum class you can simply extend this class, and make a call to <yourEnumClass>::init() before you use the enum.
 * Preferably this call is made directly after the class declaration. 
 * Example usages:
 * DaysOfTheWeek.class.php
 * abstract class DaysOfTheWeek extends Enum{
 *      static $MONDAY = 1;
 *      static $TUESDAY;
 *      static $WEDNESDAY;
 *      static $THURSDAY;
 *      static $FRIDAY;
 *      static $SATURDAY;
 *      static $SUNDAY;
 * }
 * DaysOfTheWeek::init();
 * 
 * example.php
 * require_once("DaysOfTheWeek.class.php");
 * $today = date('N');
 * if ($today == DaysOfTheWeek::$SUNDAY || $today == DaysOfTheWeek::$SATURDAY)
 *      echo "It's weekend!";
 * 
 * Flags.class.php
 * abstract class Flags extends Enum{
 *      static $FLAG_1;
 *      static $FLAG_2;
 *      static $FLAG_3;
 * }
 * Flags::init(Enum::$BINARY_FLAG);
 * 
 * example2.php
 * require_once("Flags.class.php");
 * $flags = Flags::$FLAG_1 | Flags::$FLAG_2;
 * if ($flags & Flags::$FLAG_1)
 *      echo "Flag_1 is set";
 * 
 * @author Tiddo Langerak
 */
abstract class Enum{

    static $BINARY_FLAG = 1;
    /**
     * This function must be called to initialize the enumeration!
     * 
     * @param bool $flags If the USE_BINARY flag is provided, the enum values will be binary flag values. Default: no flags set.
     */ 
    public static function init($flags = 0){
        //First, we want to get a list of all static properties of the enum class. We'll use the ReflectionClass for this.
        $enum = get_called_class();
        $ref = new ReflectionClass($enum);
        $items = $ref->getStaticProperties();
        //Now we can start assigning values to the items. 
        if ($flags & self::$BINARY_FLAG){
            //If we want binary flag values, our first value should be 1.
            $value = 1;
            //Now we can set the values for all items.
            foreach ($items as $key=>$item){
                if (!isset($item)){                 
                    //If no value is set manually, we should set it.
                    $enum::$key = $value;
                    //And we need to calculate the new value
                    $value *= 2;
                } else {
                    //If there was already a value set, we will continue starting from that value, but only if that was a valid binary flag value.
                    //Otherwise, we will just skip this item.
                    if ($key != 0 && ($key & ($key - 1) == 0))
                        $value = 2 * $item;
                }
            }
        } else {
            //If we want to use regular indices, we'll start with index 0.
            $value = 0;
            //Now we can set the values for all items.
            foreach ($items as $key=>$item){
                if (!isset($item)){
                    //If no value is set manually, we should set it, and increment the value for the next item.
                    $enum::$key = $value;
                    $value++;
                } else {
                    //If a value was already set, we'll continue from that value.
                    $value = $item+1;
                }
            }
        }
    }
}

SplEnum クラスを使用してネイティブにビルドできるようになりました。公式ドキュメントに従って。

  

SplEnumは、列挙オブジェクトをエミュレートおよび作成する機能を提供します   PHPのネイティブ。

<?php
class Month extends SplEnum {
    const __default = self::January;

    const January = 1;
    const February = 2;
    const March = 3;
    const April = 4;
    const May = 5;
    const June = 6;
    const July = 7;
    const August = 8;
    const September = 9;
    const October = 10;
    const November = 11;
    const December = 12;
}

echo new Month(Month::June) . PHP_EOL;

try {
    new Month(13);
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}
?>

インストールが必要な拡張機能ですが、デフォルトでは利用できないことに注意してください。これは、php Webサイト自体で説明されている特殊タイプの下にあります。上記の例は、PHPサイトから引用したものです。

受け入れられた答えは、進むべき道であり、実際に私がシンプルにするためにやっていることです。列挙のほとんどの利点が提供されます(読み取り可能、高速など)。ただし、1つの概念が欠落しています。タイプセーフです。ほとんどの言語では、列挙も許可された値を制限するために使用されます。以下は、プライベートコンストラクター、静的インスタンス化メソッド、およびタイプチェックを使用して、タイプセーフティを取得する方法の例です。

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

 private $intVal;
 private function __construct($intVal){
   $this->intVal = $intVal;
 }

 //static instantiation methods
 public static function MONDAY(){
   return new self(self::Monday);
 }
 //etc.
}

//function using type checking
function printDayOfWeek(DaysOfWeek $d){ //compiler can now use type checking
  // to something with $d...
}

//calling the function is safe!
printDayOfWeek(DaysOfWeek::MONDAY());

さらに先へ進むこともできます。DaysOfWeekクラスで定数を使用すると、誤用につながる可能性があります。誤って次のように使用する可能性があります。

printDayOfWeek(DaysOfWeek::Monday); //triggers a compiler error.

これは間違っています(整数定数を呼び出します)。定数の代わりにプライベート静的変数を使用してこれを防ぐことができます:

class DaysOfWeeks{

  private static $monday = 1;
  //etc.

  private $intVal;
  //private constructor
  private function __construct($intVal){
    $this->intVal = $intVal;
  }

  //public instantiation methods
  public static function MONDAY(){
    return new self(self::$monday);
  }
  //etc.


  //convert an instance to its integer value
  public function intVal(){
    return $this->intVal;
  }

}

もちろん、整数定数にアクセスすることはできません(これが実際の目的でした)。 intValメソッドを使用すると、DaysOfWeekオブジェクトを整数表現に変換できます。

列挙が広範囲に使用される場合にメモリを節約するために、インスタンス化メソッドにキャッシュメカニズムを実装することでさらに先に進むことができることに注意してください...

これが役立つことを願って

ここにいくつかの良い解決策があります!

こちらが私のバージョンです。

  • 強く型付けされている
  • IDE自動補完で動作します
  • 列挙型は、コードと説明で定義されます。コードは、整数、バイナリ値、短い文字列、または基本的に必要なものであれば何でもかまいません。パターンは、ortherプロパティをサポートするように簡単に拡張できます。
  • 値(==)と参照(===)の比較をサポートし、switchステートメントで機能します。

主な欠点は、静的メンバーの宣言時にオブジェクトを構築できないという記述とPHPのために、enumメンバーを個別に宣言およびインスタンス化する必要があることです。これを回避する方法は、代わりに解析されたドキュメンテーションコメントでリフレクションを使用することかもしれません。

抽象列挙型は次のようになります。

<?php

abstract class AbstractEnum
{
    /** @var array cache of all enum instances by class name and integer value */
    private static $allEnumMembers = array();

    /** @var mixed */
    private $code;

    /** @var string */
    private $description;

    /**
     * Return an enum instance of the concrete type on which this static method is called, assuming an instance
     * exists for the passed in value.  Otherwise an exception is thrown.
     *
     * @param $code
     * @return AbstractEnum
     * @throws Exception
     */
    public static function getByCode($code)
    {
        $concreteMembers = &self::getConcreteMembers();

        if (array_key_exists($code, $concreteMembers)) {
            return $concreteMembers[$code];
        }

        throw new Exception("Value '$code' does not exist for enum '".get_called_class()."'");
    }

    public static function getAllMembers()
    {
        return self::getConcreteMembers();
    }

    /**
     * Create, cache and return an instance of the concrete enum type for the supplied primitive value.
     *
     * @param mixed $code code to uniquely identify this enum
     * @param string $description
     * @throws Exception
     * @return AbstractEnum
     */
    protected static function enum($code, $description)
    {
        $concreteMembers = &self::getConcreteMembers();

        if (array_key_exists($code, $concreteMembers)) {
            throw new Exception("Value '$code' has already been added to enum '".get_called_class()."'");
        }

        $concreteMembers[$code] = $concreteEnumInstance = new static($code, $description);

        return $concreteEnumInstance;
    }

    /**
     * @return AbstractEnum[]
     */
    private static function &getConcreteMembers() {
        $thisClassName = get_called_class();

        if (!array_key_exists($thisClassName, self::$allEnumMembers)) {
            $concreteMembers = array();
            self::$allEnumMembers[$thisClassName] = $concreteMembers;
        }

        return self::$allEnumMembers[$thisClassName];
    }

    private function __construct($code, $description)
    {
        $this->code = $code;
        $this->description = $description;
    }

    public function getCode()
    {
        return $this->code;
    }

    public function getDescription()
    {
        return $this->description;
    }
}

具体的な列挙型の例を次に示します。

<?php

require('AbstractEnum.php');

class EMyEnum extends AbstractEnum
{
    /** @var EMyEnum */
    public static $MY_FIRST_VALUE;
    /** @var EMyEnum */
    public static $MY_SECOND_VALUE;
    /** @var EMyEnum */
    public static $MY_THIRD_VALUE;

    public static function _init()
    {
        self::$MY_FIRST_VALUE = self::enum(1, 'My first value');
        self::$MY_SECOND_VALUE = self::enum(2, 'My second value');
        self::$MY_THIRD_VALUE = self::enum(3, 'My third value');
    }
}

EMyEnum::_init();

次のように使用できます:

<?php

require('EMyEnum.php');

echo EMyEnum::$MY_FIRST_VALUE->getCode().' : '.EMyEnum::$MY_FIRST_VALUE->getDescription().PHP_EOL.PHP_EOL;

var_dump(EMyEnum::getAllMembers());

echo PHP_EOL.EMyEnum::getByCode(2)->getDescription().PHP_EOL;

そしてこの出力を生成します:

  

1:最初の値

     

array(3){
       [1] =&gt;
       object(EMyEnum)#1(2){
         [&quot;コード&quot;:&quot; AbstractEnum&quot;:private] =&gt;
         int(1)
         [&quot; description&quot;:&quot; AbstractEnum&quot;:private} =&gt;
         string(14)&quot;最初の値&quot;
       }
       [2] =&gt;
       object(EMyEnum)#2(2){
         [&quot;コード&quot;:&quot; AbstractEnum&quot;:private] =&gt;
         int(2)
         [&quot; description&quot;:&quot; AbstractEnum&quot;:private} =&gt;
         string(15)&quot; 2番目の値&quot;
       }
       [3] =&gt;
       object(EMyEnum)#3(2){
         [&quot;コード&quot;:&quot; AbstractEnum&quot;:private] =&gt;
         int(3)
         [&quot; description&quot;:&quot; AbstractEnum&quot;:private} =&gt;
         string(14)&quot; 3番目の値&quot;
       }
     }

     

2番目の値

class DayOfWeek {
    static $values = array(
        self::MONDAY,
        self::TUESDAY,
        // ...
    );

    const MONDAY  = 0;
    const TUESDAY = 1;
    // ...
}

$today = DayOfWeek::MONDAY;

// If you want to check if a value is valid
assert( in_array( $today, DayOfWeek::$values ) );

リフレクションを使用しないでください。コードについて推論し、何かが使用されている場所を追跡することが非常に難しくなり、静的分析ツール(IDEに組み込まれているものなど)が破損する傾向があります。

ここでの他の回答のいくつかに欠けている側面の1つは、型ヒントで列挙型を使用する方法です。

enumを抽象クラスの一連の定数として定義する場合、例:

abstract class ShirtSize {
    public const SMALL = 1;
    public const MEDIUM = 2;
    public const LARGE = 3;
}

関数パラメーターにヒントを入力することはできません-インスタンス化することはできませんが、 ShirtSize :: SMALL の型は int であるため ShirtSize ではありません。

だからこそ、PHPのネイティブ列挙型は、私たちが思いつくものよりもずっと優れているのです。ただし、enumの値を表すプライベートプロパティを保持し、このプロパティの初期化を定義済みの定数に制限することで、enumを近似できます。列挙型が任意にインスタンス化されるのを防ぐため(ホワイトリストの型チェックのオーバーヘッドなしで)、コンストラクターをprivateにします。

class ShirtSize {
    private $size;
    private function __construct ($size) {
        $this->size = $size;
    }
    public function equals (ShirtSize $s) {
        return $this->size === $s->size;
    }
    public static function SMALL () { return new self(1); }
    public static function MEDIUM () { return new self(2); }
    public static function LARGE () { return new self(3); }
}

この場合、 ShirtSize を次のように使用できます。

function sizeIsAvailable ($productId, ShirtSize $size) {
    // business magic
}
if(sizeIsAvailable(

ここでの他の回答のいくつかに欠けている側面の1つは、型ヒントで列挙型を使用する方法です。

enumを抽象クラスの一連の定数として定義する場合、例:

abstract class ShirtSize {
    public const SMALL = 1;
    public const MEDIUM = 2;
    public const LARGE = 3;
}

関数パラメーターにヒントを入力することはできません-インスタンス化することはできませんが、 ShirtSize :: SMALL の型は int であるため ShirtSize ではありません。

だからこそ、PHPのネイティブ列挙型は、私たちが思いつくものよりもずっと優れているのです。ただし、enumの値を表すプライベートプロパティを保持し、このプロパティの初期化を定義済みの定数に制限することで、enumを近似できます。列挙型が任意にインスタンス化されるのを防ぐため(ホワイトリストの型チェックのオーバーヘッドなしで)、コンストラクターをprivateにします。

class ShirtSize {
    private $size;
    private function __construct ($size) {
        $this->size = $size;
    }
    public function equals (ShirtSize $s) {
        return $this->size === $s->size;
    }
    public static function SMALL () { return new self(1); }
    public static function MEDIUM () { return new self(2); }
    public static function LARGE () { return new self(3); }
}

この場合、 ShirtSize を次のように使用できます。

<*>

このように、ユーザーの観点からの最大の違いは、定数の名前に()を追加する必要があることです。

1つの欠点は、 == がtrueを返すと、 === (オブジェクトの等価性を比較する)がfalseを返すことです。そのため、ユーザーが === == を使用することを忘れないように、 equals メソッドを提供するのが最善です。 > 2つの列挙値を比較します。

編集:既存のいくつかの回答は非常によく似ています。特に、 https://stackoverflow.com/a/25526473/2407870

GET["id"], ShirtSize::LARGE())) { echo "Available"; } else { echo "Out of stock."; } $s2 = ShirtSize::SMALL(); $s3 = ShirtSize::MEDIUM(); echo $s2->equals($s3) ? "SMALL == MEDIUM" : "SMALL != MEDIUM";

このように、ユーザーの観点からの最大の違いは、定数の名前に()を追加する必要があることです。

1つの欠点は、 == がtrueを返すと、 === (オブジェクトの等価性を比較する)がfalseを返すことです。そのため、ユーザーが === == を使用することを忘れないように、 equals メソッドを提供するのが最善です。 > 2つの列挙値を比較します。

編集:既存のいくつかの回答は非常によく似ています。特に、 https://stackoverflow.com/a/25526473/2407870

@Brian Clineの答えを踏む5セントを与えると思った

<?php 
/**
 * A class that simulates Enums behaviour
 * <code>
 * class Season extends Enum{
 *    const Spring  = 0;
 *    const Summer = 1;
 *    const Autumn = 2;
 *    const Winter = 3;
 * }
 * 
 * $currentSeason = new Season(Season::Spring);
 * $nextYearSeason = new Season(Season::Spring);
 * $winter = new Season(Season::Winter);
 * $whatever = new Season(-1);               // Throws InvalidArgumentException
 * echo $currentSeason.is(Season::Spring);   // True
 * echo $currentSeason.getName();            // 'Spring'
 * echo $currentSeason.is($nextYearSeason);  // True
 * echo $currentSeason.is(Season::Winter);   // False
 * echo $currentSeason.is(Season::Spring);   // True
 * echo $currentSeason.is($winter);          // False
 * </code>
 * 
 * Class Enum
 * 
 * PHP Version 5.5
 */
abstract class Enum
{
    /**
     * Will contain all the constants of every enum that gets created to 
     * avoid expensive ReflectionClass usage
     * @var array
     */
    private static 

@Brian Clineの答えを踏む5セントを与えると思った

<*>constCacheArray = []; /** * The value that separates this instance from the rest of the same class * @var mixed */ private

@Brian Clineの答えを踏む5セントを与えると思った

<*>value; /** * The label of the Enum instance. Will take the string name of the * constant provided, used for logging and human readable messages * @var string */ private

@Brian Clineの答えを踏む5セントを与えると思った

<*>name; /** * Creates an enum instance, while makes sure that the value given to the * enum is a valid one * * @param mixed $value The value of the current * * @throws \InvalidArgumentException */ public final function __construct($value) { $constants = self::_getConstants(); if (count($constants) !== count(array_unique($constants))) { throw new \InvalidArgumentException('Enums cannot contain duplicate constant values'); } if ($name = array_search($value, $constants)) { $this->_value = $value; $this->_name = $name; } else { throw new \InvalidArgumentException('Invalid enum value provided'); } } /** * Returns the constant name of the current enum instance * * @return string */ public function getName() { return $this->_name; } /** * Returns the value of the current enum instance * * @return mixed */ public function getValue() { return $this->_value; } /** * Checks whether this enum instance matches with the provided one. * This function should be used to compare Enums at all times instead * of an identity comparison * <code> * // Assuming EnumObject and EnumObject2 both extend the Enum class * // and constants with such values are defined * $var = new EnumObject('test'); * $var2 = new EnumObject('test'); * $var3 = new EnumObject2('test'); * $var4 = new EnumObject2('test2'); * echo $var->is($var2); // true * echo $var->is('test'); // true * echo $var->is($var3); // false * echo $var3->is($var4); // false * </code> * * @param mixed|Enum $enum The value we are comparing this enum object against * If the value is instance of the Enum class makes * sure they are instances of the same class as well, * otherwise just ensures they have the same value * * @return bool */ public final function is($enum) { // If we are comparing enums, just make // sure they have the same toString value if (is_subclass_of($enum, __CLASS__)) { return get_class($this) === get_class($enum) && $this->getValue() === $enum->getValue(); } else { // Otherwise assume $enum is the value we are comparing against // and do an exact comparison return $this->getValue() === $enum; } } /** * Returns the constants that are set for the current Enum instance * * @return array */ private static function _getConstants() { if (self::

@Brian Clineの答えを踏む5セントを与えると思った

<*>constCacheArray == null) { self::

@Brian Clineの答えを踏む5セントを与えると思った

<*>constCacheArray = []; } $calledClass = get_called_class(); if (!array_key_exists($calledClass, self::

@Brian Clineの答えを踏む5セントを与えると思った

<*>constCacheArray)) { $reflect = new \ReflectionClass($calledClass); self::

@Brian Clineの答えを踏む5セントを与えると思った

<*>constCacheArray[$calledClass] = $reflect->getConstants(); } return self::

@Brian Clineの答えを踏む5セントを与えると思った

<*>constCacheArray[$calledClass]; } }

これは、「動的」に関する私の見解です。列挙型...変数を使用して呼び出すことができるように、ex。フォームから。

このコードブロックの下の更新されたバージョンを見る...

$value = "concert";
$Enumvalue = EnumCategory::enum($value);
//$EnumValue = 1

class EnumCategory{
    const concert = 1;
    const festival = 2;
    const sport = 3;
    const nightlife = 4;
    const theatre = 5;
    const musical = 6;
    const cinema = 7;
    const charity = 8;
    const museum = 9;
    const other = 10;

    public function enum($string){
        return constant('EnumCategory::'.$string);
    }
}

更新:より良い方法...

class EnumCategory {

    static $concert = 1;
    static $festival = 2;
    static $sport = 3;
    static $nightlife = 4;
    static $theatre = 5;
    static $musical = 6;
    static $cinema = 7;
    static $charity = 8;
    static $museum = 9;
    static $other = 10;

}

通話

EnumCategory::${$category};

昨日、このクラスを私のブログで書きました。 PHPスクリプトで簡単に使用できると思います。

final class EnumException extends Exception{}

abstract class Enum
{
    /**
     * @var array ReflectionClass
     */
    protected static $reflectorInstances = array();
    /**
     * Массив конфигурированного объекта-константы enum
     * @var array
     */
    protected static $enumInstances = array();
    /**
     * Массив соответствий значение->ключ используется для проверки - 
     * если ли константа с таким значением
     * @var array
     */
    protected static $foundNameValueLink = array();

    protected $constName;
    protected $constValue;

    /**
     * Реализует паттерн "Одиночка"
     * Возвращает объект константы, но но как объект его использовать не стоит, 
     * т.к. для него реализован "волшебный метод" __toString()
     * Это должно использоваться только для типизачии его как параметра
     * @paradm Node
     */
    final public static function get($value)
    {
        // Это остается здесь для увеличения производительности (по замерам ~10%)
        $name = self::getName($value);
        if ($name === false)
            throw new EnumException("Неизвестая константа");
        $className = get_called_class();    
        if (!isset(self::$enumInstances[$className][$name]))
        {
            $value = constant($className.'::'.$name);
            self::$enumInstances[$className][$name] = new $className($name, $value);
        }

        return self::$enumInstances[$className][$name];
    }

    /**
     * Возвращает массив констант пар ключ-значение всего перечисления
     * @return array 
     */
    final public static function toArray()
    {
        $classConstantsArray = self::getReflectorInstance()->getConstants();
        foreach ($classConstantsArray as $k => $v)
            $classConstantsArray[$k] = (string)$v;
        return $classConstantsArray;
    }

    /**
     * Для последующего использования в toArray для получения массива констант ключ->значение 
     * @return ReflectionClass
     */
    final private static function getReflectorInstance()
    {
        $className = get_called_class();
        if (!isset(self::$reflectorInstances[$className]))
        {
            self::$reflectorInstances[$className] = new ReflectionClass($className);
        }
        return self::$reflectorInstances[$className];
    }

    /**
     * Получает имя константы по её значению
     * @param string $value
     */
    final public static function getName($value)
    {
        $className = (string)get_called_class();

        $value = (string)$value;
        if (!isset(self::$foundNameValueLink[$className][$value]))
        {
            $constantName = array_search($value, self::toArray(), true);
            self::$foundNameValueLink[$className][$value] = $constantName;
        }
        return self::$foundNameValueLink[$className][$value];
    }

    /**
     * Используется ли такое имя константы в перечислении
     * @param string $name
     */
    final public static function isExistName($name)
    {
        $constArray = self::toArray();
        return isset($constArray[$name]);
    }

    /**
     * Используется ли такое значение константы в перечислении
     * @param string $value
     */
    final public static function isExistValue($value)
    {
        return self::getName($value) === false ? false : true;
    }   


    final private function __clone(){}

    final private function __construct($name, $value)
    {
        $this->constName = $name;
        $this->constValue = $value;
    }

    final public function __toString()
    {
        return (string)$this->constValue;
    }
}

使用法:

class enumWorkType extends Enum
{
        const FULL = 0;
        const SHORT = 1;
}

指摘されたソリューションはうまく機能します。清潔で滑らか。

ただし、強く型付けされた列挙が必要な場合は、これを使用できます:

class TestEnum extends Enum
{
    public static $TEST1;
    public static $TEST2;
}
TestEnum::init(); // Automatically initializes enum values

次のようなEnumクラス:

class Enum
{
    public static function parse($enum)
    {
        $class = get_called_class();
        $vars = get_class_vars($class);
        if (array_key_exists($enum, $vars)) {
            return $vars[$enum];
        }
        return null;
    }

    public static function init()
    {
        $className = get_called_class();
        $consts = get_class_vars($className);
        foreach ($consts as $constant => $value) {
            if (is_null($className::$constant)) {
                $constantValue = $constant;
                $constantValueName = $className . '::' . $constant . '_VALUE';
                if (defined($constantValueName)) {
                    $constantValue = constant($constantValueName);
                }
                $className::$constant = new $className($constantValue);
            }
        }
    }

    public function __construct($value)
    {
        $this->value = $value;
    }
}

このように、列挙値は強く型付けされ、

TestEnum :: $ TEST1 === TestEnum :: parse( 'TEST1')// trueステートメント

ブライアンクラインの回答に基づいてライブラリを作成しました。名前は greg0ire / enum です。 お楽しみください!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top