PHP8. enum analysis of 1

Posted by neoboffins on Thu, 09 Dec 2021 07:53:07 +0100

PHP8. After the release, there are many things to pay attention to in an enum

enum is basically a restricted class. Let's look at its syntax first

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, followed by: (string|int) is optional. Because it is a class, it can implement interfaces implementation someinterface and moreinterface, and Zend is added_ ACC_ Final is equivalent to final class className, so it cannot inherit other enumeration types

definition

<?php

//Without initializing the value, it is possible to define it directly
enum Week {
    case Monday;
}

//This is an error. The initialization value of the enumeration element must specify the variable type of the entire enumeration type, string or int
enum Week {
    case Monday = 'monday';  
}

//The right way
enum Week: string {
    case Monday = 'monday';
}

Some specific operations of enum

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

//Gets the value of an enumeration type element
echo Week::Monday->value;

//Gets the key of the enumeration type element
echo Week::Monday->name;

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

Note that enumeration types cannot be instantiated, and there are no constructors and destructors. If you instantiate Week with new, 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 of week. The difference between tryFrom and from is that if a non-existent value is passed, the form will report an error, while tryFrom returns null

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

//Do not use tryFrom
try {
    $value = Week::from('no_exists_value')->value;
} catch (Throwable $e) {
    $value = null;
}

//Use tryFrom to add new syntax
$value = Week::tryFrom('no_exists_value')?->value;

Tips: the from and tryFrom methods cannot be overridden

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 ordinary classes, instance - > method name, so just remember that Week::Monday returns an instance, and other operations are highly similar to classes.

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 using trait

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

enum Week: string {
    use Testable;

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

enum get instance list

<?php

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

var_dump(Week::cases());

Tips: the cases method cannot be overridden 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, some functions of ordinary classes can also be used by enum, such as instanceof
<?php

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

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

Comparison between ENUM and common classes

ENUMGeneral class
ConstructorI won't support itsupport
DestructorI won't support itsupport
Serialization functionI won't support itsupport
Deserialization functionI won't support itsupport
Clone functionI won't support itsupport
Class propertiesI won't support itsupport
Dynamic propertiesI won't support itsupport
Instantiate with newI won't support itsupport

Topics: PHP enum PHP8