Can I use string concatenation to define a class CONST in PHP?

前端 未结 5 1665
一个人的身影
一个人的身影 2020-11-30 09:54

I know that you can create global constants in terms of each other using string concatenation:

define(\'FOO\', \'foo\');
define(\'BAR\', FOO.\'bar\');  
echo         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 10:16

    Imho, this question deserves an answer for PHP 5.6+, thanks to @jammin comment

    Since PHP 5.6 you are allowed to define a static scalar expressions for a constant:

    class Foo { 
      const BAR = "baz";
      const HAZ = self::BAR . " boo\n"; 
    }
    

    Although it is not part of the question, one should be aware of the limits of the implementation. The following won't work, although it is static content (but might be manipulated at runtime):

    class Foo { 
      public static $bar = "baz";
      const HAZ = self::$bar . " boo\n"; 
    }
    // PHP Parse error:  syntax error, unexpected '$bar' (T_VARIABLE), expecting identifier (T_STRING) or class (T_CLASS)
    
    class Foo { 
      public static function bar () { return "baz";}
      const HAZ = self::bar() . " boo\n"; 
    }
    // PHP Parse error:  syntax error, unexpected '(', expecting ',' or ';'
    

    For further information take a look at: https://wiki.php.net/rfc/const_scalar_exprs and http://php.net/manual/en/language.oop5.constants.php

提交回复
热议问题