简体   繁体   中英

PHP Equivalent of Java Type-Casting Solution

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM