开发者

Dynamic Variables Within Functions

Why does this work:

function myfunction($v) {
    $query = $v['host'] == '1';
    return ( $query );
}

$output = array_filter($recordset,myfunction);
print_r($output);

Whereas this script, which tries to accomplish the same thing with variables, does not?

$column1 = 'host';
$value1 = 1;
$query1 = '$v[\''.$column1.'\'] == '.$value1;

function myfunction($v) {
    $query = $GLOBALS['query1'];
    return ( $query );
}

$output = array_filter($recordset,myfunction);
print_r($output);

Any help would be g开发者_StackOverflow中文版reat. Thanks!


The statement $query = $v['host'] == '1'; doesn't set $query to be the expression $v['host'] == '1'. It evaluates $v['host'] == '1' and sets $query to the value of the expression, which is 1 or 0, depending on whether $v['host'] is equal to '1'.

$output = array_filter($recordset,myfunction); works because array_filter is meant to take a user-defined PHP callback function for its second argument.

Dynamic coding is really only achievable in PHP using the eval function (highly dangerous!) or using an object-oriented structure with object overloading.


Can you use global $query1?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜