如何在不使用 eval() 的情况下计算 PHP 表达式
How to evaluate a PHP expression without using eval()
我想通过将变量名传递给函数来显示变量或数组并显示它,而不必使用 dangerous eval()
函数。我无法实现它。可以吗?
代码如下:
show( '$_SESSION', 'a' ); // it does not work
show( '_SESSION', 'a' ); // it does not work
function show( $showWhat = null, $showType = null ) {
echo '<pre>';
if( strtolower( $showType ) == 'a' ) { // 'a' represents array()'s
print_r( '$' . $showWhat ); // it does not work
print_r( $showWhat ); // it does not work
}
else { // 'v' represents variables
echo $showWhat;
}
echo '</pre>';
exit;
}
根本不需要使用eval
。
像这样调用函数
show( '_SESSION', 'a' );
这会起作用
print_r( $$showWhat );
完整代码:
show( '_SESSION', 'a' );
function show( $showWhat = null, $showType = null ) {
echo '<pre>';
if( strtolower( $showType ) == 'a' ) { // 'a' represents array()'s
print_r( $$showWhat ); // it does work
}
else { // 'v' represents variables
echo $showWhat;
}
echo '</pre>';
exit;
}
更新:
对于超级全局变量 (SESSION, SERVER etc)
你应该使用 global
关键字。
$context = '_SESSION';
global $$context;
if(isset($$context)) {
print_R($$context);
}
经过大量的试验和测试,我让它以这种方式工作:
show( $_SESSION );
/**
* halts processing and displays arrays & variables
*/
function show( $showWhat = null ) {
echo '<pre>';
if( is_array( $showWhat ) ) {
echo 'Array: ';
print_r( $showWhat );
}
else {
echo 'Variable: ';
echo $showWhat;
}
echo '</pre>';
exit;
} /* show() */
我想通过将变量名传递给函数来显示变量或数组并显示它,而不必使用 dangerous eval()
函数。我无法实现它。可以吗?
代码如下:
show( '$_SESSION', 'a' ); // it does not work
show( '_SESSION', 'a' ); // it does not work
function show( $showWhat = null, $showType = null ) {
echo '<pre>';
if( strtolower( $showType ) == 'a' ) { // 'a' represents array()'s
print_r( '$' . $showWhat ); // it does not work
print_r( $showWhat ); // it does not work
}
else { // 'v' represents variables
echo $showWhat;
}
echo '</pre>';
exit;
}
根本不需要使用eval
。
像这样调用函数
show( '_SESSION', 'a' );
这会起作用
print_r( $$showWhat );
完整代码:
show( '_SESSION', 'a' );
function show( $showWhat = null, $showType = null ) {
echo '<pre>';
if( strtolower( $showType ) == 'a' ) { // 'a' represents array()'s
print_r( $$showWhat ); // it does work
}
else { // 'v' represents variables
echo $showWhat;
}
echo '</pre>';
exit;
}
更新:
对于超级全局变量 (SESSION, SERVER etc)
你应该使用 global
关键字。
$context = '_SESSION';
global $$context;
if(isset($$context)) {
print_R($$context);
}
经过大量的试验和测试,我让它以这种方式工作:
show( $_SESSION );
/**
* halts processing and displays arrays & variables
*/
function show( $showWhat = null ) {
echo '<pre>';
if( is_array( $showWhat ) ) {
echo 'Array: ';
print_r( $showWhat );
}
else {
echo 'Variable: ';
echo $showWhat;
}
echo '</pre>';
exit;
} /* show() */