简体   繁体   中英

php variable undefined in codeigniter controller, var_dump returns value

I have this code in a codeigniter controller that's the beginnings of a pagination/sorting feature for a table in the view. I'm passing order_by as a query parameter and then this is part of the controller action:

if ($order_by)
{
  function compare_items ($a, $b){
    return $b['value'][$order_by] <=> $a['value'][$order_by];
  };
  usort($data['items'], 'compare_items');
}

The problem is...I keep getting the error Undefined variable: order_by .

Since I'm checking that $order_by exists in the if statement, why am I getting this error? Even putting var_dump() inside the if statement returns a string that matches whatever I put in the query param. And hardcoding a value ( return $b['value']['<test_param>'] <=> $a['value']['<test_param>']; ) works just fine, even when if leave the if statement as is.

Is there some php scope behavior I'm not aware of that's causing this error? I'm really a javascript/React dev, and I'm hoping I'm just missing something simple in php.

You must use "use" for external variables

if ($order_by)
{
    usort($data['items'], function ($a, $b) use ($order_by) {
        return $b['value'][$order_by] <=> $a['value'][$order_by];
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM