Interpolation (double quoted string) of Associative Arrays in PHP

两盒软妹~` 提交于 2019-11-26 11:50:07

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.

To answer your question, yes, yes it can, and much like implode and explode, php is very very forgiving... so inconsistency abound

And I have to say I like PHP's interpolation for basical daisy punching variables into strings then and there,

However if your doing only string variable interpolation using a single array's objects, it may be easier to write a template which you can daisy print a specific object variables into (like in say javascript or python) and hence explicit control over the variable scope and object being applied to the string

I though this guy's isprintf really useful for this kind of thing

http://www.frenck.nl/2013/06/string-interpolation-in-php.html

<?php

$values = array(
    'who'   => 'me honey and me',
    'where' => 'Underneath the mango tree',
    'what'  => 'moon',
);

echo isprintf('%(where)s, %(who)s can watch for the %(what)s', $values);

// Outputs: Underneath the mango tree, me honey and me can watch for the moon
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!