PHP and Enumerations

后端 未结 30 1538
有刺的猬
有刺的猬 2020-11-22 13:39

I know that PHP doesn\'t have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values whi

30条回答
  •  情话喂你
    2020-11-22 14:00

    Finally, A PHP 7.1+ answer with constants that cannot be overridden.

    /**
     * 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.
    }
    

    If you are using namespaces, code completion should work.

    However, in doing this, you loose the ability to hide the constants within the class family (protected) or class alone (private). By definition, everything in an Interface is public.

    PHP Manual: Interfaces

提交回复
热议问题