PHP and Downcasting?

16 04 2010

Recently, a recruiter arranged for a perspective employer to call and conduct a 20 minute technical interview with me for a PHP Developer position. During the course of the technical questions directed my way, one in particular truly stunned me. The interviewer asked, “What does it mean to downcast an object?” I racked my brains trying to recall everything I had ever learned about doing OOP with PHP and drew a blank. The best I could do was to admit that despite my Zend certification in PHP5 and my extensive professional experience as a PHP Developer, I was unable to answer the question.

Afterwards, I searched online and learned that downcasting is a feature in some modern programming languages whereby you can take an object in a base class and cast it as an object in a subclass. There is good reason, too, as to why up to now I had yet to deal with downcasting as a PHP Developer. PHP doesn’t have downcasting as a language feature. That’s right, downcasting is unsupported in PHP!

If PHP were to support downcasting, the code might look like this:

// this won't work in PHP but illustrates the idea of downcasting
class Base {}
class SubClass extends Base {}
$b = new Base;
$subclassed = (SubClass) $b;

You can find downcasting in languages such as JAVA, C++ and C#. There are also plenty of online discussions arguing the merits of this OOP concept. Apparently, the designers of PHP were uncomfortable about having PHP support it, either because they felt it was in itself just plain, bad or else they felt it was unsuitable for PHP, perhaps because of it being a loosely-typed language. I did find a curious link to an article about how you can do some trickery with PHP to effectively downcast an object.

In case you may be curious as to how to do downcasting in a language that supports it, here’s a link that shows how to do it in C#.

This work is licensed under a Creative Commons License




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: