|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-08-11 16:30 UTC] martin dot leucht at gmail dot com
Description: ------------ Type casting in PHP is currently limited to the builtin types. It would be very useful (IMO) if one could cast a value/variable to a class. And also type hinting could be improved by casting instead of type checking only. I suggest to solve this by introducing a new magic method for classes, called "__cast()", that accepts the value to cast as parameter. I see two possible solutions for its functionality: (1) __cast() replaces the constructor method This will force the developer to move logics from the constructor into a separate function/method (which isn't even so bad) or to copy his code (which is indeed bad). If the function returns with the boolean value "false", the default error mechanism is started saying something like "cast to XYZ not allowed". (2) __cast() acts like a static constructor The code must return the casted result itself. That means one would implement some logics to transform the given value to the needed constructor parameters and create a new instance on his own. To handle an unsupported value the method would throw an exception or an error. The negative (or let's say curious) thing about this solution is, that this cast method could also return a value of a totally different type (see example). Test script: --------------- // see patch file Expected result: ---------------- // working cast Actual result: -------------- // parse errors Patchesexample-cast-magic-method (last revision 2010-08-11 14:32 UTC by martin dot leucht at googlemail dot com)Pull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Oct 28 01:00:01 2025 UTC |
I think solution 2 would be better since that would also allow caching objects: public static function __cast($id) { if (!isset(self::$cache[$id])) self::$cache[$id] = new self($id); return self::$cache[$id]; }