PHP语法${quot;字段";}


PHP Syntax ${"field"}

我不认识${"item_$I"}的PHP语法;item_$i可以是item_1到item_6。${}在作业中表示什么?我在搜索中找不到一个例子。

if($cl_name=='A') $data = ${"item_$i"};

谢谢你的帮助。

它被称为Complex (curly) syntax

这并不是因为语法复杂而被称为复杂,而是因为它允许使用复杂的表达式。

任何带有字符串表示的标量变量、数组元素或对象属性都可以通过此语法包含在内。只需以与字符串外部相同的方式编写表达式,然后将其封装在{和}中。由于{无法转义,只有当$紧跟在{后面时,才能识别此语法。使用{''$来获取文本{$。一些示例可以清楚地表明这一点:

<?php
// Show all errors
error_reporting(E_ALL);
$great = 'fantastic';
// Won't work, outputs: This is { fantastic}
echo "This is { $great}";
// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
// Works
echo "This square is {$square->width}00 centimeters broad."; 

// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";

// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"; 
// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";
// Works.
echo "This works: " . $arr['foo'][3];
echo "This works too: {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";
echo "This is the value of the var named by the return value of getName(): {${getName()}}";
echo "This is the value of the var named by the return value of '$object->getName(): {${$object->getName()}}";
// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>