Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to evaluate constants inside double quotes? [duplicate]

Tags:

php

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.

like image 767
GarouDan Avatar asked Apr 13 '13 00:04

GarouDan


People also ask

What constants must be included in double quotes?

String constants must begin and end with quotation marks.

How can I escape a double quote inside double quotes?

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 ( ' ).

How can I add double quotes to a string that is inside a variable?

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.

Is it better to use single quotes or double quotes in Javascript?

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!


2 Answers

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'));
like image 103
deceze Avatar answered Sep 25 '22 14:09

deceze


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')}";
like image 28
GarouDan Avatar answered Sep 25 '22 14:09

GarouDan