开发者

PHP constant string square bracket indexing

I'm trying to get a constant string and index it as if it was an array of characters (square bracket syntax). When I try this code it fails on the last line.

define( 'CONSTANT_STRING','0123456789abcdef');
echo CONSTANT_STRING; // Works by itself :)
$string = CONSTANT_STRING;
echo $st开发者_C百科ring[9]; // Also works by itself.
echo strlen(CONSTANT_STRING); // Also works by itself.

echo substr(CONSTANT_STRING, 9, 1); // Ok, yes this works, but not as clean.

echo CONSTANT_STRING[9]; // Fails as a syntax (parse) error.

I am using a constant string like this in a function. Since it could be called multiple times on one page it really should be a constant. What is the best option if there is no way to do this like I originally intended.


PHP Constants can only be scalar values, so the engine doesn't try to properly parse a constant that's used as something more than a scalar, like an array or an object.

This is a problem in your case because the brackets are used to point at an array index and can be used as a shortcut to grab a character at a specific location in the string.

You'll just have to do it the "hard" way and use substr().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜