使用 eval() 检查是否设置了常量
Using eval() to check if constant isset
我正在尝试根据传递变量的单个部分来检查定义的变量。 (变量的其余部分是静态的,它的所有其他部分都是相同的),所以我做了一个测试,看看这是否可行。
它不起作用,但也许我正在做一些很容易修复的小事。
define('TEST', 'works');
$test = 't';
echo TES . strtoupper($test);
echo eval('TES . strtoupper('.$test.');');
echo eval('TES . strtoupper(\'$test\');');
echo eval('TES' . strtoupper($test) . ';');
这应该适合你:
只需使用constant()
将常量名称构建为字符串,然后将其传递给函数。
echo constant("TES". strtoupper($test));
输出:
works
如果要检查常量是否定义,只需使用defined()
<?php
if (defined('TEST')) {
echo TEST;
}
?>
'TEST'
不是全局变量。这是一个constant。常量具有全局范围,可以从任何上下文访问它们(前提是您知道要使用的常量的名称)。无需使用 eval()
.
进行任何破解
如果由于某种原因在运行时生成常量名称,可以使用PHP函数defined()
to check if there is a constant already defined having that name and, if the constant exists, you can get its value using the function constant()
像这样:
define('TEST', 'works');
$test = 't';
echo 'TES'.strtoupper($test);
// Compute the constant's name
$name = 'TES'.strtoupper($test);
// Check if the constant exists and get its value
if (defined($name)) {
echo("The constant '".$name."' is already defined.\n");
echo("It's value is: ".constant($name)."\n");
}
我正在尝试根据传递变量的单个部分来检查定义的变量。 (变量的其余部分是静态的,它的所有其他部分都是相同的),所以我做了一个测试,看看这是否可行。
它不起作用,但也许我正在做一些很容易修复的小事。
define('TEST', 'works');
$test = 't';
echo TES . strtoupper($test);
echo eval('TES . strtoupper('.$test.');');
echo eval('TES . strtoupper(\'$test\');');
echo eval('TES' . strtoupper($test) . ';');
这应该适合你:
只需使用constant()
将常量名称构建为字符串,然后将其传递给函数。
echo constant("TES". strtoupper($test));
输出:
works
如果要检查常量是否定义,只需使用defined()
<?php
if (defined('TEST')) {
echo TEST;
}
?>
'TEST'
不是全局变量。这是一个constant。常量具有全局范围,可以从任何上下文访问它们(前提是您知道要使用的常量的名称)。无需使用 eval()
.
如果由于某种原因在运行时生成常量名称,可以使用PHP函数defined()
to check if there is a constant already defined having that name and, if the constant exists, you can get its value using the function constant()
像这样:
define('TEST', 'works');
$test = 't';
echo 'TES'.strtoupper($test);
// Compute the constant's name
$name = 'TES'.strtoupper($test);
// Check if the constant exists and get its value
if (defined($name)) {
echo("The constant '".$name."' is already defined.\n");
echo("It's value is: ".constant($name)."\n");
}