# Typecasting objects with __toString function

- Thread: https://externals.io/message/45416
- Original archive: https://news-web.php.net/php.internals/45416
- Started by Thomas Vanhaniemi on 2009-08-27T08:01:05+00:00
- Messages: 1
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #45416 — Thomas Vanhaniemi — 2009-08-27T08:01:05+00:00

URL: https://externals.io/message/45416#45416

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
