2

A way to cast to user object

Posted by PHPVote 9 years ago

We have the ability to cast to scalar type like : ```php $str = "42 I'm a string !"; $a = (int) $str; echo $a; // 42 ``` But it's not possible for us to cast to an object we define ! ```php $objectB = new MyB(); $objectA = (MyA) $objectB; ``` In case $objectA doesn't have the same properties than $objectB a Fatal Error could be raise. The open question would be : - Should we control the cast via a magic method ? Like : ```php class MyB { // ... public function __cast($type){ if($type == 'MyA'){ return // something with this object; } throw new ExceptionCast("This cast is not supported !"); } } ``` What do you think about that ?
erikjwaxx ยท 5 years ago