I know that you can create global constants in terms of each other using string concatenation:
define('FOO', 'foo'); define('BAR', FOO.'bar'); echo BAR;
will print 'foobar'.
However, I'm getting an error trying to do the same using class constants.
class foobar { const foo = 'foo'; const foo2 = self::foo; const bar = self::foo.'bar'; }
foo2 is defined without issue, but declaring const bar will error out
Parse error: syntax error, unexpected '.', expecting ',' or ';'
I've also tried using functions like sprintf() but it doesn't like the left paren any more than the string concatenator '.'.
So is there any way to create class constants in terms of each other in anything more than a trivial set case like foo2?
Prepend and Append Strings in PHPYou can use the concatenation operator . if you want to join strings and assign the result to a third variable or output it. This is useful for both appending and prepending strings depending on their position. You can use the concatenating assignment operator .
Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.
Concatenation Operator ("."): In PHP, this operator is used to combine the two string values and returns it as a new string.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
The only way is to define() an expression and then use that constant in the class
define('foobar', 'foo' . 'bar'); class Foo { const blah = foobar; } echo Foo::blah;
Another option is to go to bugs.php.net and kindly ask them to fix this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With