0

I'm currently using PDO and classes to return results from database queries. When I fetch back the results, they are return within an object, which contains an array of fields and values that I can access (shown below).

Array ( [0] => stdClass Object 
    ( [id] => 30 [added] => 27/05/2015 14:49:23 [addedBy] => 1 [title] => Peanut Butter Jelly Time! [category] => 6 [date_time] => 17/06/2015 [date_time_unix] => 1434495600 [venue] => 4 [duration_start] => 07:40 [duration_end] => 08:05 [tutor] => 1 [text] => Description [outline] => [book_by] => 11/06/2015 [book_by_unix] => 1433977200 ) 
)

I have a function that allows me to access the first row of results from a query, as follows:

// Return First results only
public function first(){
    return $this->results()[0];
}

This works fine on one of my servers running PHP version 5.4+. However, I have a server running PHP version 5.3.18 (which currently is unavailable for upgrade). As the array declaration '[]' was introduced in versions PHP 5.4+, it doesn't work on the server running version 5.3.18. Is there a deprecated function that I can use as a temporary measure to replace the square brackets? I've searched the web for a while and haven't managed to find anything that works.

Thank you in advance.

1 Answers1

1

The problem actually isn't [] array declaration, which is short-hand for array(), and doesn't appear in the code you shown.

However, also introduced in PHP 5.4 was the possibility of accessing array elements directly from function calls that returned an array. That's what you're doing in $this->results()[0];.

If you instead use a temporary variable to store the results of the function call first, you can return the element on the next line. Like this:

public function first(){
    $results = $this->results();
    return $results[0];
}
Joel Hinz
  • 24,719
  • 6
  • 62
  • 75