views:

157

answers:

2

Since PHP has no custom-class type-casting, how would I go about doing the PHP equivalent of this Java code:

CustomBaseObject cusBaseObject = cusBaseObjectDao.readCustomBaseObjectById(id);
((CustomChildObject) cusBaseObject).setChildAttribute1(value1);
((CustomChildObject) cusBaseObject).setChildAttribute2(value2);

In my case, it would very nice if I could do this. However, trying this without type-casting support, it gives me an error that the methods do not exist for the object.

Thanks,

Steve

+1  A: 

In PHP you just call methods. The type is a runtime attribute:

$baseObj = $baseObjDao->readById($id);
$baseObj->setChildAttribute1($value1);
$baseObj->setChildAttribute2($value2);

Java is statically (and strongly) typed. PHP is dynamically (and weakly) typed. So just call methods on objects and if it's not the right type, it'll generate a runtime error.

cletus
The problem is that for the second and third lines, the base object actually needs to be a child object. Otherwise, it will say the method does not exist because the readById() method returned the base object not child object.
stjowa
@stjowa not sure I understand what the problem is. `readById()` can return an instance of *any* class. Shouldn't it return one of the right type (the one with those methods)? If not, I'm missing something. What is Java doing that you expect?
cletus
@cletus I wasn't sure if it was correct to include/couple child-related information in a base DAO... but, I guess that was my problem in this case. In Java, I *could* have done something similar to what I wrote in my question by explicitly casting it to the child, but this is a limitation in PHP. Thanks.
stjowa
+1  A: 

The correct way to do this is to make cusBaseObjectDao::readCustomBaseObjectById() a factory that produces the appropriate child. After that there's no need to cast because PHP is a dynamic language.

Ignacio Vazquez-Abrams