开发者

Is there an integer equivalent of __toString()

Is there a way to tell PHP how to convert your objects to ints? Ideally it would look something like

class ExampleClass
{
    ...

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

    public function __toInt()
   开发者_如何学编程 {
        return $this->getId();
    }
}

I realize it's not supported in this exact form, but is there an easy (not-so-hacky) workaround?

---------------------- EDIT EDIT EDIT -----------------------------

Thanks everybody! The main reason I'm looking into this is I'd like to make some classes (form generators, menu classes etc) use objects instead of arrays(uniqueId => description). This is easy enough if you decide they should work only with those objects, or only with objects that extend some kind of generic object superclass.

But I'm trying to see if there's a middle road: ideally my framework classes could accept either integer-string pairs, or objects with getId() and getDescription() methods. Because this is something that must have occurred to someone else before I'd like to use the combined knowledge of stackoverflow to find out if there's a standard / best-practice way of doing this that doesn't clash with the php standard library, common frameworks etc.


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.


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) {
        // ....
    }
}


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


__toString() exists as a magic method.

http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring

__toInt() does not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜