[nycphp-talk] Object conversion
Andrew Yochum
andrew at plexpod.com
Mon Jan 30 21:25:02 EST 2006
On Mon, Jan 30, 2006 at 01:30:00PM -0700, Alexander wrote:
> Hello,
>
> I'm kind of newbie in PHP and especially in OO PHP.
> I was wondering whether object conversion is possible if one is derived
> from another , like this:
>
> clase Base { .. }
>
> class A extends Base { .. }
>
> will that be possible to:
>
> $objBase = new Base();
> $objA = new A();
>
> $objA = $objBase;
What you've done above is make $objA a reference to $objBase - no
"conversion".
You might've meant you'd like to downcast it to a Base object. TMK,
downcasting is not supported at all in PHP. It is commonly frowned upon in
other languages because of problems that can arise. In fact Java 1.5 even
added features 5 which resemble, or are even identical to templates in C++
(shudder<andrew> ... ;-) to avoid having to do it in the common cases like
collections. Anyway, I digress...
If you were to do this in PHP it *might* resemble its counterparts in
other languages:
$objAlikeBase = (Base) $objA;
But like I said, you can't in PHP. You may only cast between the
primatives, not classes.
If you really think you need to do this, give a better example of what
your looking to do.
Don't forget that an instance of class that extends another has the
methods and properties of *both* classes or even interfaces. It can
also be used as both when code requires it like:
class shape { }
interface printable{ }
class circle extends shape implements printable { }
function draw(shape $o) { }
function myprint(printable $o) { }
$dot = new circle();
draw($dot);
myprint($dot);
HTH,
Andrew
--
Andrew Yochum
Plexpod
andrew at plexpod.com
718-360-0879
More information about the talk
mailing list