04 Feb

As an update to my previous lolcode post, we are fixing the GetGenre()->GetGenre() issue by calling them names. GetGenre()->GetName()

There is talk of adding __toString() functions to classes like Genres and Tags but I tend to not be a fan of automagic functions. __toString() would enable us to just call GetGenre() and if we treat the resulting object as a string, it will call GetName() behind the scenes, and if we treat it like an object it will still be an object. That is a “neat” language feature, but I believe it leads to obscurity and inconsistent behavior in certain cases.

For example, if the object is not directly treated as a string even though it needs to be a string, it __toString() will not be called, and problems will ensue. Confusing problems, because the object acts like a string, sometimes.

sloppy example code:

class notAString
    public $what;
    public function __construct($val)
        $this->what = $val;
    public function __toString()
        return $this->what;
$whatIsIt = new notAString("a string");
$isAString = is_string($whatIsIt);
$isAnObject = is_object($whatIsIt);
var_dump(array('isAString' => $isAString, 'isAnObject' => $isAnObject));
echo $whatIsIt;

'isAString' => boolean false
'isAnObject' => boolean true
a string

It fails the is_string check, so if you pass the object to a function that expects a string, and the function is smart enough to check for a string before doing anything with it, your call is going to fail and you’re going to be scratching your head wondering why.

Now imagine how confusing this would be if you were trying to debug a piece of code that you had no hand in writing, you see this object being used as a string, only you don’t know it’s an object because it’s being used as a string and that part of the cod works. “It should be declared right there, just look and you’ll see it’s an object.” Sure, or it could be passed in from another function and you haven’t looked that far up the ladder yet.

Worse, you finally figure out that it’s an object, and now you can’t figure out why it’s successfully being treated as a string elsewhere. You look at the class and you don’t see a __toString() function. You look at the parent class, no __toString() there either. Ah well, a red herring, time to move on right? Or did you give up before looking at the parent class’s parent? Was there a __toString() there? How much time was wasted trying to find that, compared to how much time the automagic __toString() function might save you as a developer?

I’d wager it’s not worth the lost time, and the added frustration.

No Comments

Posted in Coding


Leave a Reply