Is there a way to evaluate a constant inside double quotes to avoid concatenation using .
?
For example, I can do things like:
echo "$variable";
echo "{$array["index"]}";
echo "{$this->myProperty}";
Unfortunally echo "{MY_CONSTANT}" don't work.
So, is there a way to evaluate a constant like in the examples above, avoiding concatenation?
I know is there alternatives to code and get the same result, but I'm aiming at just the constants.
My motivation to this is to write sql statements, for example:
$sql = "SELECT * FROM {MY_JOIN} WHERE id > 100";
Where MY_JOIN
constant could be something like
"
orders
INNER JOIN
users
ON (orders.user_id = users.id)
"
or to avoid something like
$dir = DIRECTORY_SEPARATOR."folder1".DIRECTORY_SEPARATOR."folder2".DIRECTORY_SEPARATOR;
I know I can write something like $separator = DIRECTORY_SEPARATOR
and code
$dir = "{$separator}folder1{$separator}folder2{$separator}";
but if it is possible, I would like to do this with the constants directly.
String constants must begin and end with quotation marks.
It's done by finishing an already-opened one ( ' ), placing the escaped one ( \' ), and then opening another one ( ' ). It's done by finishing already opened one ( ' ), placing a quote in another quote ( "'" ), and then opening another one ( ' ).
The basic double-quoted string is a series of characters surrounded by double quotes. If you need to use the double quote inside the string, you can use the backslash character.
Both single (' ') and double (" ") quotes are used to represent a string in Javascript. Choosing a quoting style is up to you and there is no special semantics for one style over the other. Nevertheless, it is important to note that there is no type for a single character in javascript, everything is always a string!
No, this is simply not possible.
However, two great workarounds for your particular examples:
sprintf('SELECT ... %s ...', MY_CONSTANT);
join(DIRECTORY_SEPARATOR, array('foo', 'bar', 'baz'));
Interesting, as the links suggested, we can do this with lambda functions, very interesting.
An working example:
<?php
$constant = function($cons){
return constant($cons);
};
define('FOO', 'Hello World!');
echo "The string says {$constant('FOO')}";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With