Curly braces in string in PHP

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

What is the meaning of { } (curly braces) in string literals in PHP?

回答1:

This is the complex (curly) syntax for string interpolation. From the manual:

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

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

Often, this syntax is unnecessary. For example, this:

$a = 'abcd'; $out = "$a $a"; // "abcd abcd"; 

behaves exactly the same as this:

$out = "{$a} {$a}"; // same 

So the curly braces are unnecessary. But this:

$out = "$aefgh"; 

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

$out = "${a}efgh"; // or $out = "{$a}efgh"; 


回答2:

As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parsed by PHP, because in single quotes (' ') you'll get the literal name of variable provided:



回答3:

Example:

$number = 4; print "You have the {$number}th edition book"; //output: "You have the 4th edition book"; 

Without curly braces PHP would try to find a variable named $numberth, that doesn't exist!



回答4:

I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.

$periods=array('hour', 'day', 'month'); foreach ($periods as $period) {     $this->{'value_'.$period}=1; } 

This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.

You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.

class timevalues {                              // Database table values:     public $value_hour;      // maps to values.value_hour     public $value_day;       // maps to values.value_day     public $value_month;     // maps to values.value_month     public $values=array();      public function __construct()     {         $this->value_hour=0;         $this->value_day=0;         $this->value_month=0;         $this->values=array(             'hour'=>$this->value_hour,             'day'=>$this->value_day,             'month'=>$this->value_month,         );     } } 


回答5:

here is the code I got from one wordpress plugin

$data = $wpdb->get_results("select * from {$wpdb->prefix}download_monitor_files"); 

This is really handy technique for formatting complex strings.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!