PHP - Improve object to scalar conversion

Print
Read : 4,063 times
(2 votes, average 4.50 out of 5)



The __toString() magic method allows to convert an object to a string. This mechanism can be extended to allow converting to other scalar types. New rules can also allow converting the value, even when the specific method is not implemented.

New magic methods

The first part is easy to understand : we add three new magic methods : __toBool(), __toInt(), and __toFloat().

New conversion rules

When converting an objet to scalar, the conversion logic will be :

Here are the methods that will be searched depending on the target type :

Target Try these methods in turn...
Bool Bool Int Float String
Int Int Float String Bool
Float Float Int String Bool
String String Int Float Bool

In case of a two-step conversion, scalar conversion rules apply.

Examples

class Foo
{
public function __toInt()
{
    return 10;
}
}

//-----------------

$obj=new Foo();
var_dump($obj + 1);    // -> int(10)
var_dump($obj.'a');    // -> string(3) "10a"
echo ($obj ? 'true' : 'false')    // -> true

Conversion can fail, even when a magic method is found :

class Foo
{
public function __toString()
{
return '$ 25';
}
}

//-----------------

$obj=new Foo();
var_dump($obj + 1);    // Failure "$ 25" cannot be converted to int

When a method fails, we try the next one, if any :

class Foo
{
public function __toString()
{
return '$ 25';
}

public function __toBool()
{
return true;
}
}

//-----------------

$obj=new Foo();
var_dump($obj + 1);    // -> int(2) (__toBool() was used after string -> int conversion failed)

 
Joomla SEO powered by JoomSEF