|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-05-07 15:17 UTC] colin at sheaff dot net
Description:
------------
Global constants can be set using string concatenation and other global constants. This is useful.
Class constants cannot be set using string concatenation or any functions, although they can be set to a global constant, or another class constant. The difference in setter behavior is confusing and limits utility of class constants.
Test script:
---------------
define( 'FOO', 'foo' );
define( 'BAR', FOO . 'bar' );
echo BAR . PHP_EOL;
class Foobar {
const foo = 'foo';
const bar = self::foo . 'bar';
}
echo Foobar::bar;
Expected result:
----------------
foobar
foobar
Actual result:
--------------
Parse error: syntax error, unexpected '.', expecting ',' or ';' on line 8
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Nov 07 01:00:01 2025 UTC |
And yet the following works: define( 'FOO', 'foo' ); define( 'BAR', FOO . 'bar' ); class ThisWorks { const bar = BAR; } echo ThisWorks::bar; If class constants are really compile time dependent, why is it ok to set one to a global const value which is only evaluated at run time?In a more complicated example that shows how these dependencies are not clear-cut, the following also works: define( 'BAR', ThisWorks::foo . 'bar' ); class ThisWorks { const foo = 'foo'; const bar = BAR; } echo ThisWorks::bar; this will output 'foobar' without an error.