2012-04-23 31 views

Trả lời

4

Trong ví dụ của bạn, không có sự khác biệt. Tuy nhiên, nó rất hữu ích khi biểu thức biến phức tạp hơn, giống như một mảng có chỉ mục chuỗi. Ví dụ:

$arr['string'] = 'thing'; 

echo "Print a {$arr['string']}"; 
// result: "Print a thing"; 

echo "Print a $arr['string']"; 
// result: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE 
+0

Ahh, tôi cảm ơn rất nhiều. – Andy

4

Từ PHP.net

Complex (xoăn) cú pháp

này không được gọi là phức tạp vì cú pháp phức tạp, nhưng vì nó cho phép sử dụng biểu thức phức tạp ns.

Bất kỳ biến vô hướng, phần tử mảng hoặc thuộc tính đối tượng nào có một chuỗi đại diện có thể được bao gồm qua cú pháp này. Chỉ cần viết biểu thức giống như cách xuất hiện bên ngoài chuỗi và rồi quấn nó vào {và}. Vì {không thể được thoát, cú pháp này sẽ chỉ khi $ ngay sau {. Sử dụng {\ $ đến nhận được {$.

Ví dụ:

<?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()}"; 
?> 

Xem trang đó để biết thêm ví dụ.

Các vấn đề liên quan