-2

I am experiencing "Undefined variable" error when returning an array from a class, but I do not understand why this would happen.

If I print_r($order_ids) from within the class, there is no issue. The issue only occurs when I try to print_r($order_ids) from outside the class.

CLASS FUNCTIONS FILE

function getOrderIds($start_order, $end_order) {

    $conn = new Database();

    $sql = "SELECT order_id FROM oc_order WHERE order_status_id = '17' AND order_id BETWEEN '$start_order' AND '$end_order'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $order_ids[] = $row['order_id'];
        }
    }

    return($order_ids);

}

CALL

$order = new Order();
$order->getOrderIds($start_order, $end_order); 

print_r($order_ids);

RESULT

Notice: Undefined variable: order_ids
Syn
  • 331
  • 1
  • 13
  • 1
    Missing: $order_ids = $order->getOrderIds($start_order, $end_order); // ? – kmdm Dec 01 '17 at 08:37
  • I suggest to change `function getOrderIds($start_order, $end_order) { ` into `function getOrderIds($start_order = null, $end_order = null) { `. In case one of the two variables are empty, you can return false. – Ronnie Oosting Dec 01 '17 at 08:39

1 Answers1

2
$order = new Order();
$order_ids = $order->getOrderIds($start_order, $end_order); 

print_r($order_ids);
ggirodda
  • 770
  • 7
  • 19
  • Thank you, this works, but I'm not sure why my method did not work? My understanding was that the `return` function would define $order_ids for me. Do you know where I am going wrong with my understanding of `return`? – Syn Dec 01 '17 at 08:41
  • your variable $order_ids is defined in getOrderIds function of your class, it isn't reachable outside of this function. The return of a function returns you the value of the variable, not the variable – ggirodda Dec 01 '17 at 08:46