Query class from inside a string?
Assuming I have a class like this:
class Database
{
public static $hostname = 'localhost';
}
Is there any way to do this?
$createDatabaseQuery = "CREATE DATABASE IF NOT EXISTS Database::$hostname";
Currently I'm getting an error when trying to access the class from within the string and I'd like to avoid this:
$hostname = Database::$hostname;
$createDatabase开发者_StackOverflowQuery = "CREATE DATABASE IF NOT EXISTS $hostname";
In double quotes you can only use "variable expressions". They must always start with a $
or {$
to be interpreted. And you cannot access a class variable directly without a class qualifier.
The only workaround offerable is this:
$Database = "Database"; // class name
"CREATE DATABASE IF NOT EXISTS {$Database::$hostname}";
But that's only a different kind of worse.
And this would be the "variable expression" alternative:
$var = "mysql_real_escape_string"; // trick
"CREATE DATABASE IF NOT EXISTS {$var(Database::$hostname)}";
In some situations, using Complex (curly) syntax helps -- but not in this case, unfortunately.
Quoting the relevant portion of that page :
Using single curly braces (
{}
) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.
You'll have to end up using strings concatenations :
$createDatabaseQuery = "CREATE DATABASE IF NOT EXISTS " . Database::$hostname;
$createDatabaseQuery = "CREATE DATABASE IF NOT EXISTS ".Database::$hostname;
精彩评论