PHP Curly bracket, what's meaning in this code

2019-07-12 05:05发布

问题:

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



标签: php mybb