|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-10-05 10:35 UTC] hyponiq at gmail dot com
Description:
------------
I think it'd be a useful tool to add a __cast($to) magic function to the Classes and Objects category of PHP syntax. What said function would do is allow the programmer to specify the return values of casting a user-land object into one of the built-in data types. I.E. using (int) MyObject would invoke the __cast() method passing it the 'int' type. In such a case, the programmer could then specify what is returned when cast to, per se, int's.
<?php
class MyObject {
public $myValue = null;
public function __construct($value) {
$this->myValue = $value;
}
public function __cast($to = 'string') {
switch ($to) {
case 'string':
return 'The value of myValue is: ' . (string) $this->myValue;
case 'int':
return strlen($this->myValue);
}
}
}
$myObject = new MyObject('I am a string');
print (int) $myObject; // Output: 13
?>
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Dec 04 05:00:01 2025 UTC |
This is not possible as there are too many places where it isn't cleatr which types should be used. Let $a = new Object(); $b = new Object(); Where Object implements your __cast() method Then do $c = $a + $b; What type should be requested? - The + operator can work with integers, floats and arays. Or do $d = str_replace($a, $b, "some text"); what should be used then? - str_replace can work on strings and arrays. We have __toString for everything else use specific methids. $e = $a->toInt() + $b->toInt();