ID: 46128 Comment by: mark at hell dot ne dot jp Reported By: 131 dot php at cloudyks dot org Status: Open Bug Type: Feature/Change Request Operating System: Linux PHP Version: 5.2.6 New Comment:
Please test the following extension : http://ookoo.org/svn/snip/phpcastable/ This extension adds a "Castable" interface. Any class implementing this interface have to implement a __cast() function. This function will be called when the object needs to be casted to a type. This extension is EXPERIMENTAL and needs more testing/review before being used in any production system. Previous Comments: ------------------------------------------------------------------------ [2008-10-27 17:08:24] info at netmosfera dot it AWESOME! php developers, please, we need it!! http://bugs.php.net/bug.php?id=46404 ------------------------------------------------------------------------ [2008-10-06 04:15:03] mark at hell dot ne dot jp Backported to PHP 5.2.6 : http://ookoo.org/svn/snip/php-5.2.6_class_cast_func.patch ------------------------------------------------------------------------ [2008-10-05 16:33:07] 131 dot php at cloudyks dot org This is awesome ------------------------------------------------------------------------ [2008-10-05 08:49:55] mark at hell dot ne dot jp Did a test implementation only supporting a few types (int, float, bool, string). This works as expected. Test code: ---------- class test { public function __cast($type) { switch($type) { case 'string': return 'a string'; case 'bool': return true; case 'float': return 123.456; case 'int': return 978; default: var_dump($type); return null; } } } $t = new test(); var_dump((string)$t); var_dump((int)$t); var_dump((float)$t); var_dump((bool)$t); Result: string(8) "a string" int(978) float(123.456) bool(true) Here's the patch file for this simple implementation against PHP 5.3.0alpha2. http://ookoo.org/svn/snip/php-5.3.0alpha2_class_cast_func.patch ------------------------------------------------------------------------ [2008-09-19 15:52:29] 131 dot php at cloudyks dot org Description: ------------ The same way __toString is implemented, i suggest new magics functions __toBool, __toInt, __toArray, or maybe, as suggested on php.general, a generic magic function __cast($type){} An example of implementation could be class error extends exeption { __toBool(){return false; } } Reproduce code: --------------- <? //by C. Guthrie class MyClass { function __cast($type) { switch ($type) { case 'string': return 'Foo'; case 'array': return array('Foo'); case 'DomDocument': // etc. } } } $my = new MyClass(); $xml = (DomDocument)$foo; It would return the result of __cast called with $type == 'DomDocument'. ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=46128&edit=1