PHP

2012-04-23 3 views
5

में एक स्ट्रिंग की व्याख्या करने के लिए खुले/बंद डबल कोट के बजाय खुले/बंद घुंघराले ब्रेस के बीच अंतर मैंने PHP मैनुअल पढ़ा और यह किसी भी अंतर पर वास्तव में स्पष्ट नहीं था। मैं करने के लिए के रूप में उलझन में हूँ क्या होगा इस का उपयोग कर के बिंदु:PHP

echo "Print this {$test} here."; 

की तुलना में इस होना:

echo "Print this $test here."; 

उत्तर

4

आपके उदाहरण में, कोई अंतर नहीं है। हालांकि, यह सहायक होता है जब परिवर्तनीय अभिव्यक्ति अधिक जटिल होती है, जैसे एक स्ट्रिंग इंडेक्स वाला सरणी। उदाहरण के लिए:

$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

आह, मैं आपको बहुत धन्यवाद देता हूं। – Andy

4

से PHP.net

परिसर (घुंघराले) वाक्य रचना

यह जटिल नहीं कहा जाता है क्योंकि वाक्यविन्यास जटिल है, लेकिन क्योंकि यह जटिल अभिव्यक्ति के उपयोग की अनुमति देता है एनएस।

स्ट्रिंग प्रतिनिधित्व के साथ किसी भी स्केलर चर, सरणी तत्व या ऑब्जेक्ट प्रॉपर्टी को इस वाक्यविन्यास के माध्यम से शामिल किया जा सकता है। बस अभिव्यक्ति को वैसे ही लिखें जैसा कि यह स्ट्रिंग के बाहर दिखाई देगा, और फिर इसे {और} में लपेटें। चूंकि {भाग नहीं लिया जा सकता है, यह वाक्यविन्यास केवल तभी पहचाना जाएगा जब $ तुरंत { {\ $ से का उपयोग एक शाब्दिक {$ प्राप्त करें।

उदाहरण:

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

अधिक उदाहरण के लिए कि पेज देखें।

संबंधित मुद्दे