Interpolation (double quoted string) of Associative Arrays in PHP
Yes, you may trust it. All ways of interpolation a variable are covered in the documentation pretty well.
If you want to have a reason why this was done so, well, I can't help you there. But as always: PHP is old and has evolved a lot, thus introducing inconsistent syntax.
Yes, this is well defined behavior, and will always look for the string key 'key'
, and not the value of the (potentially undefined) constant key
.
For example, consider the following code:
$arr = array('key' => 'val');define('key', 'defined constant');echo "\$arr[key] within string is: $arr[key]";
This will output the following:
$arr[key] within string is: val
That said, it's probably not best practice to write code like this, and instead either use:
$string = "foo {$arr['key']}"
or
$string = 'foo ' . $arr['key']
syntax.
The last one is a special case handled by the PHP tokenizer. It does not look up if any constant by that name was defined, it always assumes a string literal for compatibility with PHP3 and PHP4.