|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
|
Thanks for voting! Your vote should be reflected in the statistics below.
[2008-09-19 15:52 UTC] 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'.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Oct 26 11:00:02 2025 UTC |
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.patchThis would be very useful in order to be able to define a specific evaluation method for an object as a boolean, to, for example, simplify if-switches, so you can just do: if ($obj) { //... } Here an example of a class which toggles its own value each time it's evaluated as a boolean: class ToggleObj { var $val = FALSE; function __toBool() { $ret = $this->val; $this->val = !$ret; return $ret; } } $obj = new ToggleObj; if ($obj) { //Does not enter } if ($obj) { //Now it does } Or going further, to make even table rows highlighted: foreach ($rows as $row) { ?> <tr class="<?=$obj?"":"highlighted"?>"> <td><?=$row?></td> </tr> <?php } Thanks. NeoEGM http://www.neoegm.com/I think we all need this badly. It just suits the direction in which the 5.4 is going. Regarding same functionality I think it is worth nothing that the conversion to boolean should be implicit. Otherwise such code could not work: <?php function check($response) { if ( ! $response ) die('error'); } $resp = new Response(); check($resp->isSuccessful()); check($resp); // this would fail without the cast if the conversion was explicit ?>