代码之家  ›  专栏  ›  技术社区  ›  Michael Clerx

是否有一个整数等价于\uuuToString()

php
  •  19
  • Michael Clerx  · 技术社区  · 14 年前

    有没有办法告诉PHP如何将对象转换成int?理想的情况是

    class ExampleClass
    {
        ...
    
        public function __toString()
        {
            return $this->getName();
        }
    
        public function __toInt()
        {
            return $this->getId();
        }
    }
    

    ----------------------编辑编辑编辑-----------------------------

    谢谢大家!我研究这个的主要原因是我想让一些类(表单生成器、菜单类等)使用对象而不是数组(uniqueId=>description)。如果您决定它们应该只与那些对象一起工作,或者只与扩展某种通用对象超类的对象一起工作,那么这就足够简单了。

    但我想看看是否有中间路线:理想情况下,我的框架类可以接受整数字符串对,也可以接受带有getId()和getDescription()方法的对象。因为在我想使用stackoverflow的综合知识来找出是否有一种标准/最佳实践的方法来实现这一点之前,其他人肯定会遇到这种情况 .

    3 回复  |  直到 14 年前
        1
  •  11
  •   user228395    5 年前

    恐怕没有这种事。我不太清楚你需要这个的原因是什么,但请考虑以下选项:

    添加 toInt()

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

    在类外双重施法,将得到int。

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

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

    当然了 __toString() 方法可以返回包含数字的字符串: return '123' . 类外的用法可能会将此字符串自动转换为整数。

        2
  •  2
  •   Alex Howansky    14 年前

    使对象实现ArrayAccess和迭代器。

    class myObj implements ArrayAccess, Iterator
    {
    }
    
    $thing = new myObj();
    $thing[$id] = $name;
    

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

    您可以使用重新键入:

    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