5
PHP 8.1 is released, and there are many things to pay attention to in an enum.

enum is basically a limited class, let's take a look at its grammatical structure.

enum_declaration_statement:
        T_ENUM { $<num>$ = CG(zend_lineno); }
        T_STRING enum_backing_type implements_list backup_doc_comment '{' class_statement_list '}'
            { $$ = zend_ast_create_decl(ZEND_AST_CLASS, ZEND_ACC_ENUM|ZEND_ACC_FINAL, $<num>2, $6, zend_ast_get_str($3), NULL, $5, $8, NULL, $4); }
;

enum keyword 061b1a9836bd83 starts with the optional : (string|int) , because it is a class, so the interface implement SomeInterface, MoreInterface can be implemented, and because ZEND_ACC_FINAL final class className , it is equivalent to 061b1a9836bd88, so other enumeration types cannot be inherited.

definition

<?php

//不初始化值,直接这样定义是可以的
enum Week {
    case Monday;
}

//这样是错误的,里面的枚举元素初始化值,必须指定整个枚举类型的变量类型,string 或者 int
enum Week {
    case Monday = 'monday';  
}

//正确的方式
enum Week: string {
    case Monday = 'monday';
}

Some specific operations of enum

<?php
enum Week: string {
    case Monday = 'monday';
    case Tuesday = 'tuesday';
}

//获取枚举类型元素的值
echo Week::Monday->value;

//获取枚举类型元素的key
echo Week::Monday->name;

Week::Monday is an instance of this enumeration type, which is equivalent to object of the ordinary class.

Note that the enumeration type cannot be instantiated, and there is no constructor and destructor. If you use new to instantiate Week , you will get a fatal error .

Get instance by value

enum Week: string {
    case Monday = 'monday';
    case Tuesday = 'tuesday';
}

var_dump(Week::from('monday'));
var_dump(Week::tryFrom('money'));

Week::from returns Worker::Monday , which is an instance Week tryFrom with from difference is that if you pass a value that does not exist, form reports an error and tryFrom returns null .

tryFrom with the new syntax, the code will be more streamlined.

//不使用 tryFrom
try {
    $value = Week::from('no_exists_value')->value;
} catch (Throwable $e) {
    $value = null;
}

//使用 tryFrom 加新语法
$value = Week::tryFrom('no_exists_value')?->value;
tips: The from and tryFrom methods cannot be rewritten.

enum definition method

enum Week: string {
    case Monday = 'monday';
    case Tuesday = 'tuesday';
    
    public function test() {
        echo 'test'. PHP_EOL;
    }
}

Week::Monday->test();

The call is the same as the normal class, instance -> method name, so as long as you keep in mind that Week::Monday returns an instance, other operations are highly similar to the class.

enum implementation interface

<?php
interface TestInterface {
    public function test();
}

interface MultiInterface {
    public function func();
}

enum Week: string implements TestInterface, MultiInterface {
    case Monday = 'monday';
    case Tuesday = 'tuesday';
    
    public function test() {
        echo 'test'. PHP_EOL;
    }

    public function func() {
        echo 'multi interface func'. PHP_EOL;
    }
}

enum uses trait

trait Testable {
    public function test() {
        echo 'test'.PHP_EOL;
    }
}

enum Week: string {
    use Testable;

    case Monday = 'monday';
    case Tuesday = 'tuesday';
}

enum to get a list of instances

<?php

enum Week: string {
    case Monday = 'monday';
    case Tuesday = 'tuesday';
}

var_dump(Week::cases());
tips: The cases method cannot be rewritten either.

Determine whether an enum exists

<?php

enum Week: string {
    case Monday = 'monday';
    case Tuesday = 'tuesday';
}

var_dump(enum_exists('Week'));

other

  1. Because enum is essentially a class, so some common class functions, enum can also be used, such as instanceof .
<?php

var_dump(Week::Monday instanceof Week);
  1. Using ::class to return the fully qualified name is also applicable to the enum type.
  2. The namespace is basically the same as the class.
  3. To define a string, you can also use the heredoc syntax.
<?php

enum Week: string {
    const Monday = <<<MONDAY
This is monday.
MONDAY;
}

Comparison of ENUM and ordinary classes

ENUMOrdinary
Constructornot supportsupport
Destructornot supportsupport
Serialization functionnot supportsupport
Deserialization functionnot supportsupport
Clone functionnot supportsupport
Class attributenot supportsupport
Dynamic propertiesnot supportsupport
Instantiate with newnot supportsupport

church
3.6k 声望67 粉丝