0

I'm trying to convert an object that holds a rethinkdb datetime object (provided by the PHP-RQL library) but i'm getting a fatal error saying:

Using $this when not in object context

This is an overview of the code:

$day = new stdClass;

$datetime = new DateTime();
$arrival = r\time(
    $datetime->format('Y'),
    $datetime->format('m'),
    $datetime->format('d'),
    $datetime->format('H'),
    $datetime->format('i'),
    $datetime->format('s'),
    'Z'
);

$day->arrival = $arrival;

$day = object_to_array($day);

It is in the object_to_array() function I get the fatal error, its code is:

function object_to_array($obj) {
    $array  = array(); // noisy $array does not exist
    $arrObj = is_object($obj) ? get_object_vars($obj) : $obj;
    foreach ($arrObj as $key => $val) {
        $val = (is_array($val) || is_object($val)) ? $this->getArray($val) : $val;
        $array[$key] = $val;
    }
    return $array;
}

I don't remember where I got this function came from (its not mine) but its served me well in the past.

Essentially my question is why does this object_to_array function fail?

This is what the r\time function returns (an object): https://gist.github.com/fenfe1/6676924

Note: Converting just the time object to an array works fine, but passing an object containing the time fails.

Ultimately I need to end up with an array for use in another function and as other properties will be added to the day object it would be beneficial to keep this as an object.

GordyD
  • 5,063
  • 25
  • 29
fenfe1
  • 71
  • 1
  • 6
  • What are you trying to do here? `$this->getArray($val)` $this is a reference to an object you're inside – Sterling Archer Sep 23 '13 at 21:09
  • You seem to have copy/pasted some code, and altered it somewhat without changing all the necessary bits. Replace `$this->getArray` with `object_to_array` and you'll be fine. – Wrikken Sep 23 '13 at 21:10
  • @Wrikken thanks, that fixed it, I did copy the function but that was how it came - I am going to understand how it works now though. I'm not sure how I should close this question etc. though – fenfe1 Sep 23 '13 at 21:18
  • Well, Mario's answer is correctly answering your question _why_ this fails. – Wrikken Sep 23 '13 at 21:27
  • This is not directly related to your question, but $arrival actually contains a RethinkDB query object. You still have to send it to a RethinkDB server using $arrival->run($connection); to convert it the the actual RethinkDB time object. – Daniel Mewes Sep 24 '13 at 00:44

1 Answers1

2

The error message

Using $this when not in object context

already tells you the reason why the function fails. You use $this. $this is normally used inside a class as a reference to the instantiated object, but in your case you use a simple function, so there is no object context.

Mario A
  • 3,286
  • 1
  • 17
  • 22