开发者

PHP Curly bracket, what's meaning in this code

开发者 https://www.devze.com 2023-02-01 15:13 出处:网络
I have this code (for getting a query from database, in MyBB source): $query = \"SELECT \".$fields.\" FROM {$this->table_prefix}{$table}\";

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 o开发者_开发问答f {})??

Thank you ...


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 {}.


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.


$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

0

精彩评论

暂无评论...
验证码 换一张
取 消