PHP Curly bracket, what's meaning in this code

橙三吉。 提交于 2019-12-23 23:47:34

问题


I have this code (for getting a query from database, in MyBB source):

$query = "SELECT ".$fields." FROM {$this->table_prefix}{$table}";

My question is: What's meaning of {$table}? and what the difference between $table and {$table} (what's meaning of {})??

Thank you ...


回答1:


The braces simply sequester the variable names from the rest of the text (and other variable names). Generally, this syntax is used for consistency's sake; it's sometimes necessary when you have variables that run into other letters, but many programmers use it all the time so that they never have to think about whether it's necessary.

See the documentation.




回答2:


It's the PHP syntax for inlining expressions within double quotes. If you have simple expressions such as variable name, you can just use $table without bothering about {}.




回答3:


$query = "SELECT ".$fields." FROM {$this->table_prefix}{$table}";

Would execute identically to

$query = "SELECT ".$fields." FROM $this->table_prefix$table";

Using curly braces is good practice for readable code when using variables within strings (especially for those without syntax hightlighting / color blindness).

sample:

<?php
class simple
{
    function __construct()
    {
        $this->table_prefix = "blablabla";
    }

    function doSomething()
    {
        $fields = "1,2,3";
        $table = "MyTable";
        $query = "SELECT ".$fields." FROM $this->table_prefix$table";
        return $query;
    }  
}
$a = new simple(); 
print $a->doSomething();

?>

Ta



来源:https://stackoverflow.com/questions/4563728/php-curly-bracket-whats-meaning-in-this-code

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