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:
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
Previous Comments:
------------------------------------------------------------------------
[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