0

Possible Duplicate:
Cast the current object ($this) to a descendent class

Is it possible to perform the object casting from base class object to child class object in php. My base class and child class is as follows.

<?php
class Base
{

}
class child extends Base
{
}
$b=new Base();
$c=(Child)$b;//MY QUESTION IS CAN I PERFORM THIS TASK???
?>
Community
  • 1
  • 1
Piklu Guha
  • 577
  • 2
  • 7
  • 8
  • 3
    This question has interesting answers: http://stackoverflow.com/questions/2226103/how-to-cast-objects-in-php – SirDarius Sep 06 '12 at 08:01
  • 1
    see http://stackoverflow.com/questions/2226103/how-to-cast-objects-in-php – jasir Sep 06 '12 at 08:07
  • I answered a similar question over here: http://stackoverflow.com/questions/1147109/type-casting-for-user-defined-objects/1147377#1147377 – troelskn Sep 06 '12 at 08:10
  • Let me guess, you want to use base object to perform some kind of child specific functionality -- I smell flaw in design. For this purposes there are interfaces and if really need to convert one object to another, then there is Wrapper/adapter pattern to use, and you should also check for Factory pattern while you are at it – Ivan Hušnjak Sep 06 '12 at 08:10

2 Answers2

0

No, you can not do this in PHP. Why would you, as child has everything from base in it?

JvdBerg
  • 21,777
  • 8
  • 38
  • 55
  • some time it is necessary in n-tier architecture when u will be given access to only the base class all the child classes will not be accessible from the outside of the package.What i'm saying i performed those all in .net(C#) to i'm trying to use the concept of 5 tier architecture in php – Piklu Guha Sep 06 '12 at 08:26
0

As wrote in comment, there is no such thing like casting of objects in PHP, that could be known from Java, e.g...

There is some workaround using serialization, but I consider this as a mistaken joke...

Anyway while defining a functions/methods You can type the parameter like this:

class Foo { }

class Bar {
    public function bar(Foo $foo) {
        ;
    }
}

Anyway though You still are not and will not be able to cast parent object to child class (this is not able nor in Java, vice versa is OK).

shadyyx
  • 15,825
  • 6
  • 60
  • 95