【问题标题】:Interpolation (double quoted string) of Associative Arrays in PHPPHP中关联数组的插值(双引号字符串)
【发布时间】:2011-06-11 22:49:03
【问题描述】:

当插入 PHP 的字符串索引数组元素时(5.3.3,Win32) 可能会出现以下行为:

$ha = array('key1' => 'Hello to me');

print $ha['key1'];   # correct (usual way)
print $ha[key1];     # Warning, works (use of undefined constant)

print "He said {$ha['key1']}"; # correct (usual way)
print "He said {$ha[key1]}";   # Warning, works (use of undefined constant)

print "He said $ha['key1']";   # Error, unexpected T_ENCAPSED_AND_WHITESPACE
print "He said $ha[ key1 ]";   # Error, unexpected T_ENCAPSED_AND_WHITESPACE
print "He said $ha[key1]";     # !! correct (How Comes?)

有趣的是,最后一行似乎是正确的 PHP 代码。有什么解释吗? 这个功能可信吗?


编辑:为了减少误解,现在将发帖的重点设置为粗体

【问题讨论】:

标签: php associative-array


【解决方案1】:

是的,你可以相信它。 All ways of interpolation a variable are covered in the documentation 不错。

如果您想说明这样做的原因,那么我无法为您提供帮助。但一如既往:PHP 已经很老了,并且已经发展了很多,因此引入了不一致的语法。

【讨论】:

  • @nikic,我在文档中找不到这个确切的案例(没有大括号),它在哪里?谢谢,rbo
  • @mario:我个人认为这并不好,但可能很多其他人都可以接受 -> 放弃了那部分。
  • @rubber boots: 注意这条线:echo "He drank some $juices[koolaid1] juice.".PHP_EOL;.
  • @mario,我来自 Perl(仍然住在那里),而 in Perl 的插值通常使事情更具可读性。这里的 PHP 中的 DMF(非常缺少的功能)是 Perls q-operator (quote) series -> qq{}, q{}, qx{}, qw{}。因此(恕我直言)字符串插值在 PHP 中可能没有它可能有用。 :-(
  • @nikic 以某种方式服务,对。但不是在一条线上。比较 Perl:$x = qq{$text};
【解决方案2】:

是的,这是定义明确的行为,并且将始终查找字符串键 'key',而不是(可能未定义的)常量 key 的值。

例如,考虑以下代码:

$arr = array('key' => 'val');
define('key', 'defined constant');
echo "\$arr[key] within string is: $arr[key]";

这将输出以下内容:

$arr[key] within string is: val

也就是说,编写这样的代码可能不是最佳做法,而是使用:

$string = "foo {$arr['key']}"

$string = 'foo ' . $arr['key']

语法。

【讨论】:

    【解决方案3】:

    最后一个是 PHP 分词器处理的特殊情况。如果定义了该名称的任何常量,它不会查找,它总是假定一个字符串文字以与 PHP3 和 PHP4 兼容。

    【讨论】:

    • 只为那些感兴趣的人(可能没有人......):PHP 将为数组索引生成一个T_STRING(如果它是一个非溢出十进制数,则为一个T_NUM_STRING)而不是正常T_CONSTANT_ENCAPSED_STRING.
    【解决方案4】:

    要回答你的问题,是的,是的,它可以,就像内爆和爆炸一样,php 非常宽容......所以不一致的地方比比皆是

    我不得不说我喜欢 PHP 的插值,用于将基本的菊花冲入字符串中,然后在那里,

    但是,如果您只使用单个数组的对象进行字符串变量插值,则编写一个模板可能会更容易,您可以将特定对象变量菊花打印到其中(比如在 javascript 或 python 中),从而显式控制变量作用于字符串的范围和对象

    我虽然这家伙的 isprintf 对于这种事情真的很有用

    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
    

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多