Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
<?php
// 显示所有错误
error_reporting(E_ALL);
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
// 正确的
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
// 不正确的。 这可以工作,但也会抛出一个 E_NOTICE 级别的 PHP 错误,因为
// 未定义名为 apple 的常量
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
//print $arr[fruit]; // apple
// 这定义了一个常量来演示正在发生的事情。 值 'veggie'
// 被分配给一个名为 fruit 的常量。
define('fruit', 'veggie');
// 注意这里的区别
print $arr['fruit']; // apple
print $arr[fruit]; // carrot
// 以下是可以的,因为它在字符串中。
// 不会在字符串中查找常量,因此此处不会出现 E_NOTICE
print "Hello $arr[fruit]"; // Hello apple
// 有一个例外:字符串中花括号围绕的数组中常量可以被解释
//
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple
// 这将不起作用,并会导致解析错误,例如:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// 这当然也适用于在字符串中使用超全局变量
//print "Hello $arr['fruit']";
//print "Hello $_GET['foo']";
// 串联是另一种选择
print "Hello " . $arr['fruit']; // Hello apple
?>