How to return a constant or a text string in PHP -- is eval() the way to go
I have a row in a mysql table whose column contains:
This is a test.
I have another row in the same mysql table whose same column contains:
K_IM_A_CONSTANT
Earlier on in the PHP script, this line of code exists:
define(K_IM_A_CONSTANT, 'This is a constant.');
How 开发者_Go百科can I echo the contents of the column whereby, the returned value would either be "This is a test." or "This is a constant.", depending on the row selected?
Is eval() the way to do it? If so, how might the eval() syntax look? I have been getting too many errors trying to get eval() to work.
Thanks for helping.
Use the constant
function:
if(defined($row['column_name']))
{
echo constant($row['column_name']);
}
So given a piece of text, you want to find the name of a constant whose value matches the piece of text? This seems like a hideous abuse of "constants" to me, but, you'd want to use get_defined_constants()
:
function find_constant_name($text) {
$constants = get_defined_constants();
foreach($constants as $const => $val) {
if ($val == 'Your specified text') {
return($const);
}
}
}
find_constant_name('This is a test.');
精彩评论