Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 621
selfsimilar Avatar asked May 07 '10 04:05

selfsimilar


People also ask

Can you concatenate strings in PHP?

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 .

How do you define const in class?

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.

Which of the following is used for string concatenation in PHP?

Concatenation Operator ("."): In PHP, this operator is used to combine the two string values and returns it as a new string.

What happens when concatenating strings?

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.


1 Answers

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.

like image 107
user187291 Avatar answered Oct 12 '22 19:10

user187291