PHP - define constant inside a class

后端 未结 5 1461
失恋的感觉
失恋的感觉 2020-12-05 03:55

How can I define a constant inside a class, and make it so it\'s visible only when called in a class context?

....something like Foo::app()->MYCONSTANT;

5条回答
  •  旧巷少年郎
    2020-12-05 04:32

    This is a pretty old question, but perhaps this answer can still help someone else.

    You can emulate a public constant that is restricted within a class scope by applying the final keyword to a method that returns a pre-defined value, like this:

    class Foo {
    
        // This is a private constant
        final public MYCONSTANT()
        {
            return 'MYCONSTANT_VALUE';
        }
    }
    

    The final keyword on a method prevents an extending class from re-defining the method. You can also place the final keyword in front of the class declaration, in which case the keyword prevents class Inheritance.

    To get nearly exactly what Alex was looking for the following code can be used:

    final class Constants {
    
        public MYCONSTANT()
        {
            return 'MYCONSTANT_VALUE';
        }
    }
    
    class Foo {
    
        static public app()
        {
            return new Constants();
        }
    }
    

    The emulated constant value would be accessible like this:

    Foo::app()->MYCONSTANT();
    

提交回复
热议问题