Hi!
I was testing typecasting of objects to different types. Discovered that
if you try to cast an object to other types except string you get a PHP
notice that it isn't allowed.
I'm using PHP 5.3, and it would be nice if PHP would call my __toString
function BEFORE trying to typecast. This way one can, e.g. have an own
string class and use the variables in the same way as you would use an
ordinary string variable.
Some code:
<?php
class CastTest
{
private $value;
public function __construct($value)
{
$this->value = (string)$value;
}
public function __toString()
{
return (string)$this->value;
}
}
$test1 = new CastTest('10');
$test2 = new CastTest(11);
echo "Test 1 [String: $test1, Int: " . (int)$test1 . ", Float: " .
(float)$test1 . "]\n";
echo "Test 2 [String: $test2, Int: " . (int)$test2 . ", Float: " .
(float)$test2 . "]\n";
?>
Result (excluding the PHP Notices):
Test 1 [String: 10, Int: 1, Float: 1]
Test 2 [String: 11, Int: 1, Float: 1]
Nice to have result (no notices):
Test 1 [String: 10, Int: 10, Float: 10]
Test 2 [String: 11, Int: 11, Float: 11]
Can this be fixed, or can a more generic magic function be added that
provides this functionality?
Regards,
Thomas Vanhaniemi
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php