Is there an integer equivalent of __toString()

Make your objects implement ArrayAccess and Iterator.

class myObj implements ArrayAccess, Iterator
{
}

$thing = new myObj();
$thing[$id] = $name;

Then, in the code that consumes this data, you can use the same "old style" array code that you had before:

// Here, $thing can be either an array or an instance of myObj
function doSomething($thing) {
    foreach ($thing as $id => $name) {
        // ....
    }
}

I'm afraid there is no such thing. I'm not exactly sure what the reason is you need this, but consider the following options:

Adding a toInt() method, casting in the class. You're probably aware of this already.

public function toInt()
{
    return (int) $this->__toString();
}

Double casting outside the class, will result in an int.

$int = (int) (string) $class;

Make a special function outside the class:

function intify($class)
{
    return (int) (string) $class;
}
$int = intify($class);

Of course the __toString() method can return a string with a number in it: return '123'. Usage outside the class might auto-cast this string to an integer.


You can use retyping:

class Num
{
    private $num;

    public function __construct($num)
    {
        $this->num = $num;
    }

    public function __toString()
    {
        return (string) $this->num;
    }
}

$n1 = new Num(5);
$n2 = new Num(10);

$n3 = (int) (string) $n1 + (int) (string) $n2; // 15

Tags:

Php