Re: [RFC] Custom Casting
| From: | Stas Malyshev | Date: | Sun, 13 May 2012 23:40:37 +0000 |
| Subject: | Re: [RFC] Custom Casting | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-60558@lists.php.net to get a copy of this message | ||
Hi!
> Please be kind to review and comment my proposal for custom casting in PHP
> (or let me know if a similar proposal was already discussed).
>
> http://pastebin.com/sPb0i8U6
I think there's an issue with this idea. As far as I understand, what is
proposed is kind of cast-constructor paradigm. However, the result of
(ClassName)$var would be expected to be an object of type ClassName.
That is, however, not what cast() returns - it returns integer $var.
Since there's no way for foo(ClassName $var) to know where $var came
from, the result of $var = (ClassName)$var; is just a simple integer and
foo() would reject it since it's not an object of type ClassName.
Of course, you could just create this instead:
class PositiveInteger {
private $i;
function __construct($i) {
if(intval($i) < 1) $i = 1;
$this->i = $i;
}
function intval() {
return $this->i;
}
}
function foo(PositiveInteger $i) { return 2*sqrt($i->intval()); }
and then:
foo(new PositiveInteger(42));
But this is doable right now, even if sounds a bit of overkill for me. I
wouldn't mind also having (int)$i done with some magic methods, as
proposed in RFCs you mentioned.
--
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/
(408)454-6900 ext. 227