开发者

PHP Equivalent of Java Type-Casting Solution

开发者 https://www.devze.com 2022-12-22 00:33 出处:网络
Since PHP has no custom-class type-casting, how would I go about doing the PHP equivalent of this Java code:

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

CustomBaseObje开发者_高级运维ct 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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消