开发者

Dynamic Variables Within Functions

开发者 https://www.devze.com 2022-12-31 12:06 出处:网络
Why does this work: function myfunction($v) { $query = $v[\'host\'] == \'1\'; return ( $query ); } $output = array_filter($recordset,myfunction);

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

精彩评论

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

关注公众号