php – What are the braces {} in an SQL string for?

Question:

What are the braces {} in the following SQL string used in PHP for MySQL for?

$sql = "INSERT INTO {$table} ({$fields}) VALUES ({$placeholders})"

Answer:

Braces {} followed by a dollar sign $ indicate that the complex string interpolation syntax is being used, it serves to invoke methods of an object. It also serves to display the value of a variable (a little exaggerated or necessary in a very particular case) this is only valid inside double quotes. Static members CANNOT be invoked within double quotes in which case it is mandatory to concatenate the strings

<?php
class Pessoa {
    const FOO = 'algum valor';

    public $nome = 'mario';
    public $idade = '20';
    public static $planeta = 'terra';

    public function getNumeroAleatorioDaSorte(){
        return 6;
    }
}

$pessoa = new Pessoa();

//exemplos validos:
echo "{$pessoa->getNumeroAleatorioDaSorte()} <br>";
echo "{$pessoa->nome} <br>";
echo "$pessoa->nome <br>";

//exemplos invalidos
echo "$pessoa->getNumeroAleatorioDaSorte()";
//notice: Undefined property Pessoa::$getNumeroAleatorioDaSorte

echo "Pessoa::$planeta";//notice: Undefined variable: planeta e imprime Planeta::
echo "{Pessoa::$planeta}";//notice: Undefined variable: planeta e imprime {Pessoa::}

echo "Pessoa::FOO";//imprime Pessoa::FOO
echo "{Pessoa::FOO}";//imprime {Pessoa::FOO}

Example

Scroll to Top