ou.jiayong.name

Hi, this is Jiayong Ou's blog about programming and other things he deems interesting.

He's also on Twitter as @jiayongou and short tidbits of his discoveries on the world wide web are on orly.ch. There are also pages for his other online activies, how to get in touch with him, his projects and about his person.

Fun with PHP's type juggling …NOT!

It can be argued if PHP trying to be smart when dealing with types is a good thing or not (I say it's horrible but I have to live with it), but it does produce some funny results.

Today's adventure started with a PHP error message:

PHP Fatal error:  Call to undefined method stdClass::update()

My first though was: WTF? I didn't use stdClass anywhere! So I investigated the snipped that caused it a bit

<?php
// snip...

$feed = Feed::get($id);
$feed->status = $status;
$feed->update();

// snap...

Looks normal. Maybe Feed::get() has something wrong?

<?php
class Feed {
    // some other methods
    function get($id) {
        // snip...

        return $row ? new self($row['foo'] /*, ... */) : null;
    }
}

Okay, no way that thing can get me a stdClass object. Then I tried out what would happen if null would be returned, so the first snipped $feed->status = $status would operate on a variable holding null:

$ php -r '$a = null; $a->foo = "bar"; var_dump($a);'

When I saw the result, I facepalmed. Hard.

object(stdClass)#1 (1) {
  ["foo"]=>
  string(3) "bar"
}