PHP සහ ගණන් කිරීම්


1156

PHP සතුව ස්වදේශීය ගණනය කිරීම් නොමැති බව මම දනිමි. නමුත් මම ඔවුන්ට ජාවා ලෝකයෙන් පුරුදු වී සිටිමි. IDEs ස්වයංක්‍රීයව සම්පූර්ණ කිරීමේ අංගයන් තේරුම් ගත හැකි පූර්ව නිශ්චිත අගයන් ලබා දීම සඳහා enums භාවිතා කිරීමට මම කැමතියි.

නියතයන් උපක්‍රමය කරයි, නමුත් නාම අවකාශය ision ට්ටන ගැටළුව ඇති අතර (හෝ ඇත්ත වශයෙන්ම නිසා ) ඒවා ගෝලීය ය. අරා වලට නාම අවකාශයේ ගැටලුවක් නොමැත, නමුත් ඒවා අපැහැදිලි ය, ඒවා ධාවන වේලාවේදී නැවත ලිවිය හැකි අතර IDEs යතුරු ස්වයංක්‍රීයව පුරවන්නේ කෙසේදැයි දන්නේ කලාතුරකිනි (කිසි විටෙකත්?).

ඔබ බහුලව භාවිතා කරන විසඳුම් / ක්‍රියාමාර්ග තිබේද? PHP යාලුවනේ එනූම්ස් වටා යම් සිතුවිලි හෝ තීරණ ගෙන තිබේද යන්න කිසිවෙකුට මතකද?



1
නියතයන් බිට්වේස් හෝ නැතැයි ගණනය කරන ශ්‍රිතය වටා මම කෘතියක් නිර්මාණය කළෙමි. ඔබ මීට පෙර මෙය ඇසූ බවක් දුටුවේ නැත, නමුත් මෙහි පන්ති විචල්‍යයන්ට වඩා හොඳ විසඳුමක් මා සතුව ඇත: stackoverflow.com/questions/3836385/…
NoodleOfDeath


කොන්ස්ටන්ට්ස් ගැටලුව ගැන තව ටිකක් බෙදා ගැනීමට ඔබට අවශ්‍යද? "නියතයන් උපක්‍රමය කරයි, නමුත් නාම අවකාශයේ ision ට්ටන ගැටළුව ඇති අතර (හෝ ඇත්ත වශයෙන්ම ඒවා ගෝලීය බැවින්)."
XuDing

Answers:


1496

භාවිත අවස්ථාව මත පදනම්ව, මම සාමාන්‍යයෙන් පහත සඳහන් දේ වැනි සරල දෙයක් භාවිතා කරමි :

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 විස්තාරණය කරන සරල enum පන්තියක් නිර්මාණය කිරීමෙන්, දැන් ඔබට සරල ආදාන වලංගු කිරීම සඳහා ක්‍රම භාවිතා කිරීමේ හැකියාව ඇත:

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

පැති සටහනක් ලෙස, දත්ත වෙනස් නොවන ස්ථිතික / සංයුක්ත පන්තියක අවම වශයෙන් එක් වරක් වත් මම පරාවර්තනය භාවිතා කරන විට (එනැම් වැනි), එම පරාවර්තන ඇමතුම්වල ප්‍රති c ල මම හැඹිලිගත කරමි. අවසානයේදී සැලකිය යුතු කාර්යසාධන බලපෑමක් ඇති කරයි (බහු එනූම් සඳහා ඇසෝසියේටිව් අරා තුළ ගබඩා කර ඇත).

දැන් බොහෝ මිනිසුන් ඇති බව අවසාන වශයෙන් අවම වශයෙන් 5.3 දක්වා උසස්, සහ SplEnumමෙන්ම බව නිසැකව ශක්ය විකල්පය වන අතර, ලබා ගත හැකි - ඔබ සැබෑ නිඛිල තිබීමේ සම්ප්රදායිකව unintuitive සංකල්පය කමක් නෑ තාක් කල් instantiations ඔබගේ codebase පුරා. ඉහත නිදසුනේ, BasicEnumසහ DaysOfWeekසියලු දී instantiated නොහැක, හෝ ඒවා විය යුතුය.


70
මමත් මේක පාවිච්චි කරනවා. ඔබ ද පන්ති කරමින් සලකා බැලීමට ඉඩ abstractහා finalඑය instantiated කළ නොහැකි හෝ දීර්ඝ නිසා,.
ryeguy

22
ඔබ පන්තිය ද කළ හැකි abstractහා final? මම දන්නවා ජාවා වල මේකට අවසර නැහැ. ඔබට එය php වලින් කළ හැකිද?
corsiKa

21
@ryeguy එය ඔබ එය නො හැකි ය පෙනේ දෙකම abstract හා final. එවැනි අවස්ථාවක, මම වියුක්තව යන්නෙමි.
නිකොල්

47
වියුක්ත හෝ අවසාන ගැන; මම ඒවා අවසන් කර හිස් පෞද්ගලික ඉදිකිරීම්කරුවෙකු ලබා
දෙමි

22
0 භාවිතා කිරීම ගැන සැලකිලිමත් වන්න, එබැවින් ඔබ බලාපොරොත්තු නොවූ ව්‍යාජ සංසන්දනාත්මක ගැටළු වලට නොයන්න, උදා: ප්‍රකාශයක් තුළ nullමිතුරන් හා මිතුරන් සමඟ සමාන වීම switch. එතන හිටියා.
yitznewton

185

ස්වදේශීය දිගුවක් ද තිබේ. මෙම SplEnum

SplEnum විසින් PHP හි දේශීයව ගණන් ගැනීමේ වස්තු අනුකරණය කිරීමට සහ නිර්මාණය කිරීමට හැකියාව ලබා දෙයි.

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

අවධානය:

https://www.php.net/manual/en/spl-types.installation.php

PECL දිගුව PHP සමඟ එකතු නොවේ.

මෙම PECL දිගුව සඳහා DLL දැනට නොමැත.


4
මෙන්න splenum සමඟ උදාහරණයක්: dreamincode.net/forums/topic/201638-enum-in-php
Nordes

4
මම ආපසු පෙරළා, සබැඳිය දැකිය හැකි විට මම ඊට වඩා කැමතියි. එය මට සන්දර්භය තොරතුරු ලබා දෙයි.
මාර්කස්

6
මම නැවත පෙරළා දැමුවෙමි. මට ඕන නෑ ඔයාලා සබැඳිය සංස්කරණය කරනවාට.
මාර්කස්

6
මෙය භාවිතා කිරීමට ප්‍රවේශම් වන්න. එස්පීඑල් වර්ග පර්යේෂණාත්මක ය: "මෙම දිගුව
bzeaman

6
SplEnum PHP සමඟ බැඳී නොමැත, එයට SPL_Types දිගුව
Kwadz

46

පන්ති නියතයන් ගැන කුමක් කිව හැකිද?

<?php

class YourClass
{
    const SOME_CONSTANT = 1;

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

echo YourClass::SOME_CONSTANT;

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

මම මේ සරල ප්‍රවේශයට කැමතියි
ඩේවිඩ් ලෙමන්

echoConstantආදේශ කළ හැකිය __toString. ඊට පස්සෙ සරලවමecho $c
ජස්ටිනාස්

35

ඉහත ඉහළම පිළිතුර අපූරු ය. කෙසේ වෙතත්, ඔබ extendඑය වෙනස් ආකාර දෙකකින් සිදු කරන්නේ නම්, කුමන දිගුව සිදු කළත් පළමුව ප්‍රති results ල මඟින් කාර්යයන් සඳහා ඇමතුමක් ලැබෙනු ඇත. මෙම හැඹිලිය පසුව සියලුම ඇමතුම් සඳහා භාවිතා කරනු ඇත, ඇමතුම් කුමන දිගුවකින් ආරම්භ කළත් ...

මෙය විසඳීම සඳහා විචල්‍යය ප්‍රතිස්ථාපනය කර පළමු ශ්‍රිතය:

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];
}

2
මේ ප්‍රශ්නයම තිබුණා නම්. පිළිගත් පිළිතුරෙන් බ්‍රයන් හෝ සංස්කරණ වරප්‍රසාද ඇති අය එය ස්පර්ශ කළ යුතුය. GetConstants () ශ්‍රිතයේ 'ස්වයං ::' වෙනුවට 'ස්ථිතික ::' ක්‍රමය භාවිතා කරමින් මම එය මගේ කේතයෙන් විසඳා ළමා එන්යූම්ස් හි $ constCache නැවත ප්‍රකාශ කරමි.
Sp3igel

එය සරාගී නොවිය හැකි නමුත් අතුරු මුහුණතක් නියතයක් භාවිතා කිරීම PHP තුළට යාමට හොඳම ක්‍රමය විය හැකිය.
ඇන්තනි රට්ලෙජ්

28

මම නියතයන් සමඟ පන්ති භාවිතා කළෙමි:

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

print Enum::NAME;

27

මම interfaceඒ වෙනුවට භාවිතා කරන්නේ class:

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

var $today = DaysOfWeek::Sunday;

6
class Foo implements DaysOfWeek { }ඊට පස්සේ Foo::Sunday... මොකක්ද?
ඩෑන් ලග්

3
ප්‍රශ්න කතුවරයා කරුණු දෙකක් සඳහා විසඳුමක් ඉල්ලා සිටී: නාම අවකාශය සහ IDE මඟින් ස්වයංක්‍රීයව සම්පූර්ණ කිරීම. ඉහළම ශ්‍රේණිගත කළ පිළිතුර යෝජනා කළ පරිදි, පහසුම ක්‍රමය වන්නේ class(හෝ interface, එය මනාපයක් පමණි) භාවිතා කිරීමයි.
ඇන්ඩි ටී

5
පන්ති ක්‍රියාත්මක කිරීමේ අඛණ්ඩතාව බලාත්මක කිරීම සඳහා අතුරුමුහුණත් භාවිතා කරයි, මෙය අතුරු මුහුණතක සීමාවෙන් පිටත ය
පරිශීලක 3886650

3
38 user3886650 නියත අගයන් තබා ගැනීම සඳහා අතුරුමුහුණත් ජාවා හි භාවිතා කළ හැකිය. එබැවින් ඔබට නිරන්තර අගයන් ලබා ගැනීම සඳහා පමණක් පන්තියක් ක්ෂණිකව කිරීමට බල නොකෙරෙන අතර ඕනෑම IDE එකක් මඟින් කේත සම්පූර්ණ කිරීම ඉදිරිපත් කරයි. තවද ඔබ එම අතුරු මුහුණත ක්‍රියාත්මක කරන පන්තියක් නිර්මාණය කළහොත් එය එම නියතයන් සියල්ලම උරුම කර ගනී.
ඇලෙක්ස්

38 user3886650 ඇත්ත, නමුත් PHP හි, අතුරු මුහුණත් වලට නියතයන් තිබිය හැකිය. මීට අමතරව, පංති හෝ ඔවුන්ගේ දරුවන් ක්‍රියාත්මක කිරීමෙන් මෙම අතුරුමුහුණත් නියතයන් අභිබවා යා නොහැක. ඇත්ත වශයෙන්ම, PHP අනුව මෙය හොඳම පිළිතුරයි, මන්දයත් අභිබවා යා හැකි කිසිවක් නියතයක් මෙන් සැබවින්ම ක්‍රියාත්මක නොවන බැවිනි. නියත යන්නෙන් අදහස් කළ යුත්තේ නියත, සමහර විට නොවේ (බහුමාපකය ඇතැම් විට ප්‍රයෝජනවත් විය හැකි වුවද).
ඇන්තනි රට්ලෙජ්

26

මම මෙහි වෙනත් පිළිතුරු කිහිපයක් ගැන අදහස් දක්වා ඇත, එබැවින් මම ද බර කිරා මැන බැලුවෙමි. දවස අවසානයේදී, PHP ටයිප් කළ ගණන් කිරීම් සඳහා සහය නොදක්වන බැවින්, ඔබට ක්‍රම දෙකෙන් එකක් යා හැකිය: ටයිප් කළ ගණන් කිරීම් හැක් කරන්න, නැතහොත් .ලදායි ලෙස අනවසරයෙන් ඇතුළුවීම අතිශයින් දුෂ්කර ය යන කාරණය සමඟ ජීවත් වන්න.

මම කාරණය සමඟ ජීවත් වීමට කැමැත්තෙමි, ඒ වෙනුවට 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පදනම පන්තියේ අනෙකුත් සියලු enumerations දීර්ඝ කරන සිට වැනි සහකාරියක් ක්රම සඳහා ඉඩ toArray, isValid, සහ යනාදි. මට නම්, ටයිප් කළ ගණන් ගැනීම් ( සහ ඒවායේ සිදුවීම් කළමනාකරණය කිරීම ) අවසන් වන්නේ අවුල් සහගත ය.


උපකල්පිත

නම් , එය එහි පැවති __getStatic(මැජික් ක්රමය හා වඩාත් සුදුසු වන __equalsද මැජික් ක්රමය ) මෙම බොහෝ multiton රටාව කිසියම් ආකාරයක සමග අවම කළ හැක.

( පහත දැක්වෙන්නේ උපකල්පිත ය; එය ක්‍රියා නොකරනු ඇත , සමහර විට යම් දවසක එය සිදුවනු ඇත )

final class TestEnum
{

    private static $_values = [
        'FOO' => 1,
        'BAR' => 2,
        'QUX' => 3,
    ];
    private static $_instances = [];

    public static function __getStatic($name)
    {
        if (isset(static::$_values[$name]))
        {
            if (empty(static::$_instances[$name]))
            {
                static::$_instances[$name] = new static($name);
            }
            return static::$_instances[$name];
        }
        throw new Exception(sprintf('Invalid enumeration value, "%s"', $name));
    }

    private $_value;

    public function __construct($name)
    {
        $this->_value = static::$_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

මෙම පිළිතුරේ සරලත්වයට මම ඇත්තෙන්ම කැමතියි. එය ඔබට යම් ආකාරයක අනවසර ප්‍රවේශයක් කළ බවක් නොපෙන්වා පසුකාලීනව නැවත පැමිණ එය ක්‍රියා කරන ආකාරය ඉක්මනින් තේරුම් ගත හැකි කාරණයකි. ලැජ්ජාවට එයට වැඩි ඡන්ද ප්‍රමාණයක් නොමැත.
ප්‍රතික්‍රියාකාරක

23

හොඳයි, php හි එනූම් වැනි සරල ජාවා සඳහා, මම භාවිතා කරන්නේ:

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 ආරම්භකයෙක්, වාක්‍ය ඛණ්ඩය සමඟ පොරබදමින් මෙය හොඳම ක්‍රමය නොවනු ඇත. මම පන්තියේ නියතයන් සමඟ අත්හදා බැලුවෙමි, පරාවර්තනය භාවිතා කරමින් එහි වටිනාකමෙන් නියත නම ලබා ගැනීම නියත විය හැකිය.


හොඳ පිළිතුර, අනෙක් පිළිතුරු බොහොමයක් පන්ති භාවිතා කරයි. ඔබට කැදැලි පන්ති තිබිය නොහැක.
කීඕ

පුරෝකථනය සමඟ සාරධර්ම හරහා නැවත කියවීමේ හැකියාව මෙහි ඇත. නීති විරෝධී වටිනාකමක් හසු නොවන බවට වන හානිය.
බොබ් ස්ටයින්

2
IDE හි ස්වයංක්‍රීයව සම්පූර්ණ කිරීමක් සිදු නොවීම අනුමාන වැඩ උත්තේජනය කරයි. නියතයන් ස්වයංක්‍රීයව සම්පුර්ණ කිරීමට ඉඩ සලසයි.
KrekkieD

19

අවුරුදු හතරකට පසු මට මෙය නැවත හමු විය. මගේ වර්තමාන ප්‍රවේශය මෙයයි, එය IDE හි කේත සම්පුර්ණ කිරීමට මෙන්ම ආරක්‍ෂාව ටයිප් කිරීමට ඉඩ සලසයි:

මූලික පන්තිය:

abstract class TypedEnum
{
    private static $_instancedValues;

    private $_value;
    private $_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::$_instancedValues === null)
        {
            self::$_instancedValues = array();
        }

        $className = get_called_class();

        if (!isset(self::$_instancedValues[$className]))
        {
            self::$_instancedValues[$className] = array();
        }

        if (!isset(self::$_instancedValues[$className][$value]))
        {
            $debugTrace = debug_backtrace();
            $lastCaller = array_shift($debugTrace);

            while ($lastCaller['class'] !== $className && count($debugTrace) > 0)
            {
                $lastCaller = array_shift($debugTrace);
            }

            self::$_instancedValues[$className][$value] = new static($value, $lastCaller['function']);
        }

        return self::$_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;
    }
}

උදාහරණ Enum:

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';
        // ...
}

ඔබට නම හෝ වටිනාකම අනුව enum ඇතුළත් කිරීමක් නිර්මාණය කළ හැකිය:

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

නැතහොත් ඔබට දැනට පවතින enum entry එකකින් නම (එනම් ක්‍රියාකාරී නාමය) ලබා ගත හැකිය:

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

පුද්ගලික ඉදිකිරීම්කරුවෙකු සඳහා +1. මම උපකාරක වියුක්ත පංතියක්, සරල පංතියක්, පුද්ගලික ඉදිකිරීම්කරුවෙකු සහ සමහරක් const Monday = DaysOfWeek('Monday');
නොකරමි

9

මම මෙම පුස්තකාලය ගිතුබ්හි සොයා ගත් අතර එය මෙහි ඇති පිළිතුරු සඳහා ඉතා හොඳ විකල්පයක් සපයන බව මම සිතමි.

SplEnum වෙතින් ආනුභාව ලත් PHP Enum ක්‍රියාත්මක කිරීම

  • ඔබට ටයිප්-ඉඟිය කළ හැකිය: function setAction(Action $action) {
  • ඔබට ක්‍රම මගින් එනුම් පොහොසත් කළ හැකිය (උදා format , parse, ...)
  • නව අගයන් එකතු කිරීම සඳහා ඔබට එනුම් දිගු කළ හැකිය (ඔබේ එනුම් සාදන්න 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 enum අගයන්:

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

1
මෙය නිවැරදි පිළිතුරයි (දැනට, enumPHP 7.x හි එකතු කරන තුරු ) එය ඉඟි වර්ගයට ඉඩ සලසයි.
ටොබියා

1
මෙය ටයිප්-ඉඟි කිරීමට ඉඩ දෙනවා පමණක් නොව, __toString()මැජික් නිසා, ඔබට සාමාන්‍යයෙන් එනුම් සමඟ සැබවින්ම අවශ්‍ය දේ කිරීමට ඉඩ සලසයි - ඒවා සංක්ෂිප්තයේ අගයන් සමඟ කෙලින්ම සංසන්දනය කරමින් ඒවා ප්‍රකාශයකින් switchහෝ ifප්‍රකාශයකින් භාවිතා කරන්න . ස්වදේශීය එනුම් ආධාරයෙන් කෙටිම ප්‍රවේශය, IMO.
ලිනස්ආර්

7

ඔබට ගෝලීය වශයෙන් අද්විතීය (එනම් විවිධ එනූම් අතර මූලද්‍රව්‍ය සංසන්දනය කිරීමේදී පවා) භාවිතා කිරීමට අවශ්‍ය නම් සහ භාවිතා කිරීමට පහසු නම්, පහත කේතය භාවිතා කිරීමට නිදහස් වන්න. මට ප්‍රයෝජනවත් යැයි පෙනෙන ක්‍රම කිහිපයක් ද මම එකතු කළෙමි. කේතයේ ඉහළින්ම ඇති අදහස් වලින් ඔබට උදාහරණ සොයාගත හැකිය.

<?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";
    }

}


?>

1
මම මේකට ගොඩක් කැමතියි. කෙසේ වෙතත්, මූලික පැමිණිලි වලින් එකක් වන්නේ ස්වයංක්‍රීයව සම්පුර්ණ කිරීම සඳහා වටිනාකම් ලබා ගැනීමට IDE සතු හැකියාවයි. IDE සඳහා අභිරුචි ඇඩෝනයක් නොමැතිව මෙය කළ හැකි බව මට විශ්වාස නැත. එය කළ නොහැකි බව නොවේ, එය යම් වැඩක් ගතවනු ඇත.
corsiKa

2
භාවිතා eval()ඔබට නව Enums ධාවන ප්රකාශ කළ හැකි ඉතින්? Eek. මට එය දැනෙන්නේ නැත. නිසි පන්තිය නිර්වචනය කිරීමට පෙර වෙනත් පන්ති වැරදි එනුම් පන්තියක් සෑදීම වළක්වා ගන්නේ කෙසේද? ධාවන කාලයට පෙර එනූම්ස් නොදන්නේද? Ors කෝර්සිකා ඇඟවුම් කළ පරිදි, IDE ස්වයං සම්පුර්ණ කිරීමක් නොමැත. කම්මැලි කේතීකරණය මා දකින එකම වාසිය.
KrekkieD

7

මම ජාවා වෙතින් එනූම් වලටද කැමතියි. මේ හේතුව නිසා මම මගේ එනූම්ස් මේ ආකාරයෙන් ලියමි, මම සිතන්නේ මෙය ජාවා එනුම්ස් වැනි වඩාත් සමාන හැසිරීමක් බවයි, ඇත්ත වශයෙන්ම, සමහරුන්ට ජාවා වෙතින් තවත් ක්‍රම භාවිතා කිරීමට අවශ්‍ය නම් එය මෙහි ලිවිය යුතුය, නැතහොත් වියුක්ත පංතිය නමුත් මූලික අදහස පහත කේතයට ඇතුළත් කර ඇත


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

3
කුඩා එකතු කිරීම් දෙකක් සහිතව මම එකම දේම කරමි: ස්ථිතික අගයන් පිටුපස ස්ථිතික අගයන් සඟවා ඇත. එක් හේතුවක් මම දෘශ්ය කැමති, වන FruitsEnum::Apple()අධික FruitsEnum::$Apple, නමුත් වඩා වැදගත් හේතුවක් සැකසීම සිට වෙන කිසිවෙකු වැලැක්වීම ය $APPLEඅනුව, සමස්ත අයදුම් පත්රය සඳහා නිඛිල බිඳ. අනෙක සරල පුද්ගලික ස්ථිතික ධජයක් වන අතර එය පළමු වරට ඇමතුමෙන් පසුව ඇමතුම විවෘත නොවන බවට $initializedවග බලා ගනී init()(එබැවින් කිසිවෙකුටත් එය අවුල් කළ නොහැක).
මාටින් එන්ඩර්

මම මාටින්ට කැමතියි. .init()අමුතුයි, මට එය ලබා ගැනීමේ ප්‍රවේශය කමක් නැහැ.
සෙබාස්

7
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>";
}


5

PHP හි එනූම් සඳහා මා දුටු වඩාත් පොදු විසඳුම නම් සාමාන්‍ය එනුම් පන්තියක් නිර්මාණය කර එය දිගු කිරීමයි. ඔබ දිහා විය මෙම .

යාවත්කාලීන කිරීම: විකල්පයක් ලෙස, මම මෙය phpclasses.org වෙතින් සොයා ගතිමි.


1
ක්‍රියාවට නැංවීම ඉතා සිහින් සහ බොහෝ විට එම කාර්යය කරනු ඇතත්, මෙහි අවාසිය නම් IDEs බොහෝ විට එනූම් ස්වයංක්‍රීයව පුරවන්නේ කෙසේදැයි නොදැන සිටීමයි. මට phpclasses.org වෙතින් පරීක්ෂා කිරීමට නොහැකි විය, එයට මා ලියාපදිංචි වීමට අවශ්‍ය වූ නිසාය.
හෙන්රික් පෝල්

5

Php හි ටයිප්-ආරක්ෂිත ගණනය කිරීම් හැසිරවීම සඳහා ගිතුබ් පුස්තකාලයක් මෙන්න:

මෙම පුස්තකාලය පන්ති උත්පාදනය, පන්ති හැඹිලිය හසුරුවන අතර එය එනූම්ස් සමඟ ගනුදෙනු කිරීම සඳහා උපකාරක ක්‍රම කිහිපයක් සමඟින්, ආරක්ෂිත ගණනය කිරීම් සැලසුම් රටාවක් ක්‍රියාත්මක කරයි.

ජනනය කරන ලද කේතය සාමාන්‍ය පැරණි php අච්චු ගොනුවක් භාවිතා කරයි, එයද වින්‍යාසගත කළ හැකි බැවින් ඔබට ඔබේම අච්චුවක් ලබා දිය හැකිය.

එය phpunit වලින් ආවරණය වූ සම්පූර්ණ පරීක්ෂණයකි.

ගිතුබ් මත php-enums (දෙබලක නිදහස් වන්න)

භාවිතය: (use details.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

4

ක්‍රියාකාරී පරාමිතීන් සඳහා ආරක්ෂිත ආරක්ෂාව, නෙට්බීන්ස් හි ස්වයංක්‍රීයව සම්පූර්ණ වීම සහ හොඳ ක්‍රියාකාරිත්වය සඳහා මට හැකියාව ලබා දෙන බැවින් පහත ප්‍රවේශය භාවිතා කිරීමට මම පියවර ගෙන ඇත්තෙමි. මම ඕනෑවට වඩා අකමැති එක දෙය [extended class name]::enumerate();නම් පංතිය නිර්වචනය කිරීමෙන් පසුව ඔබ ඇමතිය යුතු බවයි.

abstract class Enum {

    private $_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");

DaysOfWeek::$MONDAY = 3;
එනූම්

Rian බ්‍රයන්ෆිෂර්, මම දන්නවා දැන් එය ප්‍රමාද වැඩියි, නමුත්, ඔබ [extended class name]::enumerate();අර්ථ දැක්වීමෙන් පසුව ඇමතීමට අකමැති නම්, ඔබ එය ඉදිකිරීමේදී නොකරන්නේ ඇයි?
Can O 'Spam

4

පහත දැක්වෙන මගේ එනුම් පන්ති අර්ථ දැක්වීම තදින් ටයිප් කර ඇති අතර භාවිතා කිරීමට සහ අර්ථ දැක්වීමට ඉතා ස්වාභාවිකය .

අර්ථ දැක්වීම:

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

එනුම් මාරු කරන්න

$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 "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

එනුම් පන්තිය:

/**
 * @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();

4

මෙය ඉතා පැරණි නූලක් බව මට වැටහී ඇති නමුත් මට මේ ගැන සිතුවිල්ලක් ඇති අතර මිනිසුන් සිතන දේ දැන ගැනීමට අවශ්‍ය විය.

සටහන්: මම මේ සමඟ සෙල්ලම් කරමින් සිටියෙමි, මම __call()ශ්‍රිතය වෙනස් කළහොත් ඔබට සත්‍යයට වඩාත් සමීප විය හැකි බව මට වැටහුණි enums. මෙම __call()කාර්යය සියලු නොදන්නා ඇමතුම් ශ්රිතයක් ලබයි. එබැවින් ඔබට enumsRED_LIGHT, YELLOW_LIGHT, සහ GREEN_LIGHT තුනක් සෑදීමට අවශ්‍ය යැයි කියමු. පහත සඳහන් දෑ කිරීමෙන් ඔබට දැන් එය කළ හැකිය:

$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()ශ්‍රිතය හැඳින්වෙන්නේ (නිශ්චිත අගයක් නොමැති නිසා), එමඟින් අරාවෙහි ඇතුළත් කිරීම සිදු කර නොමැති බව පෙනේ. එබැවින් එය ප්‍රවේශය ලබා දෙයි, ප්ලස් වන් (+1) ලබා දුන් අවසාන අගය එයට පවරයි, අවසාන අගය විචල්‍යය වැඩි කරයි, සහ සත්‍යය ලබා දෙයි. ඔබ අගය සකසන්නේ නම්:

$c->RED_LIGHT = 85;

එවිට __set()ශ්‍රිතය කැඳවනු ලබන අතර අවසාන අගය නව අගයට ප්ලස් වන් (+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";

?>

3

මෙය පැරණි නූලක් බව මම දනිමි, කෙසේ වෙතත් මා දුටු කිසිදු ක්‍රියාමාර්ගයක් ඇත්ත වශයෙන්ම එනුම් ලෙස පෙනුනේ නැත, මන්දයත් සෑම ක්‍රියාමාර්ගයක්ම පාහේ ඔබට අතින් අයිතම සඳහා අගයන් පැවරීම අවශ්‍ය වන හෙයිනි, නැතහොත් ඔබට එනුම් යතුරු පෙළක් a වෙත යැවිය යුතුය. ශ්‍රිතය. ඒ නිසා මම මේ සඳහා මගේම විසඳුමක් නිර්මාණය කළා.

මගේ විසඳුම භාවිතයෙන් එනූම් පංතියක් නිර්මාණය කිරීම සඳහා කෙනෙකුට මෙම එනුම් පන්තිය පහතින් විස්තාරණය කළ හැකිය, ස්ථිතික විචල්‍යයන් රාශියක් නිර්මාණය කරන්න (ඒවා ආරම්භ කිරීමට අවශ්‍ය නැත), සහ ඔබේ එනුම් පන්තියට අර්ථ දැක්වීමට මඳක් පහළින් ඔබේ එනුම් ක්ලාස් :: init () වෙත ඇමතුමක් ලබා දෙන්න. .

සංස්කරණය කරන්න: මෙය ක්‍රියාත්මක වන්නේ php> = 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;
                }
            }
        }
    }
}

3

දැන් ඔබට එය ස්වදේශීයව තැනීමට 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 වෙබ් අඩවියේම විස්තර කර ඇති විශේෂ වර්ග යටතේ වේ. ඉහත උදාහරණය PHP අඩවියෙන් ලබාගෙන ඇත.


3

අවසාන වශයෙන්, අභිබවා යා නොහැකි නියතයන් සමඟ PHP 7.1+ පිළිතුරක්.

/**
 * An interface that groups HTTP Accept: header Media Types in one place.
 */
interface MediaTypes
{
    /**
    * Now, if you have to use these same constants with another class, you can
    * without creating funky inheritance / is-a relationships.
    * Also, this gets around the single inheritance limitation.
    */

    public const HTML = 'text/html';
    public const JSON = 'application/json';
    public const XML = 'application/xml';
    public const TEXT = 'text/plain';
}

/**
 * An generic request class.
 */
abstract class Request
{
    // Why not put the constants here?
    // 1) The logical reuse issue.
    // 2) Single Inheritance. 
    // 3) Overriding is possible.

    // Why put class constants here?
    // 1) The constant value will not be necessary in other class families.
}

/**
 * An incoming / server-side HTTP request class.
 */
class HttpRequest extends Request implements MediaTypes
{
    // This class can implement groups of constants as necessary.
}

ඔබ නාම අවකාශයන් භාවිතා කරන්නේ නම්, කේත සම්පූර්ණ කිරීම ක්‍රියාත්මක විය යුතුය.

කෙසේ වෙතත්, මෙය සිදු කිරීමේදී, පන්ති පවුල ( protected) හෝ පන්තිය තුළ පමණක් ( private) තුළ නියතයන් සැඟවීමේ හැකියාව ඔබ ලිහිල් කරයි . අර්ථ දැක්වීම අනුව, යම් සියල්ල Interfaceවේ public.

PHP අත්පොත: අතුරුමුහුණත්


මෙය ජාවා නොවේ. මව් පංතියක නියතයන් අභිබවා යාමට බහුමාපකය / උපාය මාර්ග රටාව අවශ්‍ය නොවන අවස්ථාවන්හිදී මෙය ක්‍රියාත්මක වේ.
ඇන්තනි රට්ලෙජ්

2

මෙය මගේ "ගතික" එනූම් එකයි ... එවිට මට එය විචල්යයන් සමඟ ඇමතිය හැකිය, උදා. ආකෘතියකින්.

මෙම කේත වාරණයට පහළින් යාවත්කාලීන කළ වෙරිසන් දෙස බලන්න ...

$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};

5
මෙම පැවැත්මේ ගැටලුව; EnumCategory::$sport = 9;. ක්‍රීඩා කෞතුකාගාරයට සාදරයෙන් පිළිගනිමු. const එය කිරීමට වඩා හොඳ ක්‍රමයයි.
ඩෑන් ලග්

2

පිළිගත් පිළිතුර යනු යා යුතු මාර්ගය වන අතර ඇත්ත වශයෙන්ම මම කරන්නේ සරල බව සඳහා ය. ගණන් බැලීමේ බොහෝ වාසි ලබා දෙනු ලැබේ (කියවිය හැකි, වේගවත්, ආදිය). කෙසේ වෙතත් එක් සංකල්පයක් අස්ථානගත වී ඇත: ආරක්ෂාව ටයිප් කරන්න. බොහෝ භාෂාවල, අවසර ලත් අගයන් සීමා කිරීම සඳහා ගණන් ගැනීම් ද යොදා ගනී. පහත දැක්වෙන්නේ පුද්ගලික ඉදිකිරීම්කරුවන්, ස්ථිතික ක්ෂණික ක්‍රම සහ වර්ග පරීක්ෂා කිරීම මඟින් වර්ගයේ ආරක්ෂාව ලබා ගත හැකි ආකාරය පිළිබඳ උදාහරණයකි:

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 වස්තුවක් එහි පූර්ණ සංඛ්‍යා නිරූපණයට පරිවර්තනය කිරීමට ඉඩ ලබා දේ.

ගණනය කිරීම් බහුලව භාවිතා වන අවස්ථාවකදී මතකය සුරැකීම සඳහා ක්ෂණික ක්‍රමවේදයන්හි හැඹිලි යාන්ත්‍රණයක් ක්‍රියාත්මක කිරීමෙන් අපට තවත් ඉදිරියට යා හැකි බව සලකන්න ...

මෙය උපකාරී වේ යැයි සිතමි


2

මෙහි හොඳ විසඳුම් කිහිපයක්!

මෙන්න මගේ අනුවාදය.

  • එය තදින් ටයිප් කර ඇත
  • එය IDE ස්වයංක්‍රීයව සම්පූර්ණ කිරීම සමඟ ක්‍රියා කරයි
  • කේතය පූර්ණ සංඛ්‍යාවක්, ද්විමය අගයක්, කෙටි නූලක් හෝ මූලික වශයෙන් ඔබට අවශ්‍ය ඕනෑම දෙයක් විය හැකි කේතයක් සහ විස්තරයක් මඟින් එනූම්ස් අර්ථ දක්වා ඇත. ඕතර් ගුණාංග සඳහා රටාව පහසුවෙන් දිගු කළ හැකිය.
  • එය අගය (==) සහ යොමු (===) සැසඳීම් සහ ස්විච් ප්‍රකාශ වල ක්‍රියා කරයි.

මම හිතන්නේ ප්‍රධාන අවාසිය නම් විස්තරය සහ ස්ථිතික සාමාජික ප්‍රකාශන වේලාවේදී වස්තූන් තැනීමට 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] =>
වස්තුව (EMyEnum) # 1 (2) {
["code": "AbstractEnum": private] =>
int (1)
["description": "AbstractEnum": private] =>
string (14) "මගේ පළමු අගය"
}
[2] =>
වස්තුව (EMyEnum) # 2 (2) {
["code": "AbstractEnum": private] =>
int (2)
["description": "AbstractEnum" : private] =>
string (15) "මගේ දෙවන අගය"
}
[3] =>
වස්තුව (EMyEnum) # 3 (2) {
["code": "AbstractEnum": private] =>
int (3)
["description": "AbstractEnum": private] =>
string (14) "මගේ තුන්වන අගය"
}
}

මගේ දෙවන වටිනාකම


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 තුළ ගොඩනගා ඇති දේ).


2

මෙහි ඇති වෙනත් පිළිතුරු වලින් මඟ හැරී ඇති එක් අංගයක් වන්නේ ඉඟි වර්ග ඉඟි භාවිතා කිරීමයි.

වියුක්ත පන්තියක නියත සමූහයක් ලෙස ඔබේ එනුම් අර්ථ දක්වන්නේ නම්, උදා

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

එය instantiable නෑ නිසා, පමණක් නොව, වර්ගය නිසා, එකක් සඳහා - ඔබ උත්සවයකට පරාමිතිය එය ඇතුලත් විය ටයිප් කළ නොහැකි ShirtSize::SMALLintනොව, ShirtSize.

PHP හි ස්වදේශික එනූම්ස් අපට ඉදිරිපත් කළ හැකි ඕනෑම දෙයකට වඩා හොඳ වන්නේ එබැවිනි. කෙසේ වෙතත්, අපට එනුම් වල වටිනාකම නිරූපණය කරන පුද්ගලික දේපලක් තබා ගැනීමෙන් සහ මෙම දේපල අපගේ පූර්ව නිශ්චිත නියතයන්ට සීමා කිරීමෙන් සීමා කළ හැකිය. අත්තනෝමතික ලෙස එන්යූම් ක්ෂණිකව වළක්වා ගැනීම සඳහා (සුදු ලැයිස්තුවක් ටයිප් පරීක්‍ෂා කිරීමේ පොදු කාර්යයක් නොමැතිව), අපි ඉදිකිරීම්කරු පුද්ගලික කරන්නෙමු.

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($_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";

මේ ආකාරයෙන්, පරිශීලකයාගේ දෘෂ්ටිකෝණයෙන් ඇති ලොකුම වෙනස ()නම්, නියතයේ නම මත ඔබ සම්බන්ධ විය යුතුය .

එක් අවාසියක් නම් ===(වස්තු සමානාත්මතාවය සංසන්දනය කරන) ==සත්‍ය වූ විට අසත්‍ය බවට පත්වීමයි. එම හේතුව නිසා, equalsක්‍රමයක් භාවිතා කිරීම වඩාත් සුදුසුය, එවිට පරිශීලකයින්ට භාවිතා කිරීමට මතක තබා ගත යුතු අතර එනුම් අගයන් දෙකක් සංසන්දනය ==නොකෙරේ ===.

සංස්කරණය කරන්න: පවතින පිළිතුරු කිහිපයක් ඉතා සමාන ය, විශේෂයෙන්: https://stackoverflow.com/a/25526473/2407870 .


2

Rian බ්‍රයන් ක්ලයින්ගේ පිළිතුරට පියවර තැබීමෙන් මම සිතුවේ මගේ ශත 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 $_constCacheArray = [];
    /**
     * The value that separates this instance from the rest of the same class
     * @var mixed
     */
    private $_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 $_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::$_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];
    }
}

කිසියම් හේතුවක් නිසා මට මෙම ක්‍රියාකාරකම් ලෙස හැඳින්විය නොහැක. එය මට කියා සිටින්නේ එවැනි කාර්යයන් ප්‍රකාශයට පත් නොකරන බවයි. මම වැරදි කරන්නේ කුමක්ද? [මූලික එනුම් පන්තිය වෙනත් ගොනුවක පිහිටා ඇති අතර මම භාවිතා කරමි include('enums.php');]. යම් හේතුවක් නිසා එය දකින්නේ නැත කාර්යයන් දරුවා පන්ති ... සඳහා නිඛිල දී ප්රකාශයට පත් කරන
ඇන්ඩෲ

එසේම ... එය නූල් වලින් සකසන්නේ කෙසේද? වැනි sth$currentSeason.set("Spring");
ඇන්ඩෲ

1

PHP සමඟ එනැම් එකක් සෑදීමට මා දැරූ උත්සාහය ... එය වස්තූන් එනුම් අගයන් ලෙස සහාය නොදක්වන නමුත් එය තරමක් ප්‍රයෝජනවත් බැවින් එය අතිශයින් සීමිතය ...

class ProtocolsEnum {

    const HTTP = '1';
    const HTTPS = '2';
    const FTP = '3';

    /**
     * Retrieve an enum value
     * @param string $name
     * @return string
     */
    public static function getValueByName($name) {
        return constant('self::'. $name);
    } 

    /**
     * Retrieve an enum key name
     * @param string $code
     * @return string
     */
    public static function getNameByValue($code) {
        foreach(get_class_constants() as $key => $val) {
            if($val == $code) {
                return $key;
            }
        }
    }

    /**
     * Retrieve associate array of all constants (used for creating droplist options)
     * @return multitype:
     */
    public static function toArray() {      
        return array_flip(self::get_class_constants());
    }

    private static function get_class_constants()
    {
        $reflect = new ReflectionClass(__CLASS__);
        return $reflect->getConstants();
    }
}

එය බොහෝ දිශාවලට සීමා වී ඇති අතර පවතින පිළිතුරු ඊට වඩා බොහෝ දේ ඉදිරිපත් කරයි. මම කියන්නේ මෙය සැබවින්ම ප්‍රයෝජනවත් කිසිවක් එකතු නොකරන බවයි.
hakre

1

ඊයේ මම මගේ බ්ලොග් අඩවියේ මෙම පන්තිය ලිවීය . මම හිතන්නේ එය 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;
}

2
නමුත් එය හොඳ පංතියක් වන අතර කාර්යයන් නම් ස්වදේශීය වේ. එසේම translate.google.ru උදව් විය හැකිය.
Arturgspb

2
ක්‍රෝම් යාලුවනේ භාවිතා කර එය පරිවර්තනය කරන්න, ඔබ ක්‍රමලේඛකයින් නම්, ඔබ කේතය කියවයි!
මාර්කස්

8
පොදුවේ ගත් කල, 'n' මාස / අවුරුදු හෝ ඊට වැඩි කාලයක් තුළ තිබිය හැකි හෝ නොවිය හැකි බාහිර සම්පතක් සමඟ සම්බන්ධ වීමට වඩා, පිළිතුර තුළ කේතය ඇතුළත් කිරීම වඩා හොඳය
ජෝන් පාකර්

මගේ පංතිය එතරම් විශාල වන අතර මෙම ලිපිය කියවීම අපහසු වනු ඇතැයි මම සිතමි.
Arturgspb

මම හිතන්නේ මෙහි නරක දේවල් දෙකක් තිබේ: එය රුසියානු භාෂාවෙන් (සෑම ක්‍රමලේඛකයෙක්ම ඉංග්‍රීසි දැන සිටිය යුතු අතර අදහස් දැක්වීමේදී පවා එය භාවිතා කළ යුතුය) සහ එය මෙහි ඇතුළත් නොවේ. විශාල කේත ඇතුළත් කරන්නේ කෙසේදැයි උදව් බලන්න.
gaRex
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.