PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 1, 2022

[FIXED] Accessing php variable from within function scope

 January 01, 2022     codeigniter, php     No comments   

Issue

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.


Solution

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];
    });
}


Answered By - Isaac Limón
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing