PHP - define constant inside a class

后端 未结 5 1465
失恋的感觉
失恋的感觉 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:30

    You can define a class constant in php. But your class constant would be accessible from any object instance as well. This is php's functionality. However, as of php7.1, you can define your class constants with access modifiers (public, private or protected).

    A work around would be to define your constant as private or protected and then make them readable via a static function. This function should only return the constant values if called from the static context.

    You can also create this static function in your parent class and simply inherit this parent class on all other classes to make it a default functionality.

    Credits: http://dwellupper.io/post/48/defining-class-constants-in-php

提交回复
热议问题