drxzpo70788179614 2013-10-27 21:25
浏览 39
已采纳

对于PHP中的其他简单类型,__toString()方法是否相同?

_toString() is called when an object is used as string. How can I do something similar for numerical values, something like __toInt(), or __toArray(). Do such methods exist? Is there a work around? Is it a bad idea to use something like that even if there is a workaround for it?

  • 写回答

1条回答 默认 最新

  • dpus81500574 2013-10-27 21:36
    关注

    There is no __toArray magic-method (just check the ones that exist here), but then, there shouldn't be, IMO.
    Though people have asked for a magic toArray method, it doesn't look like such a method will be implemented any time soon.

    Considering what objects are for, and how we use them, a toInt method wouldn't make much sense, and since all objects can be cast to an array, and can be iterated over, I see very little point in using __toArray anyway.
    To "convert" on object to an array, you can use either one of the following methods:

    $obj = new stdClass;
    $obj->foo = 'bar';
    var_dump((array) $obj);
    //or
    var_dump(json_decode(json_encode($obj), true));
    

    This can be done with both custom objects, as stdClass instances alike.
    As far as accessing them as an array, I can't see the point. Why write a slow magic method to be able to do something like:

    $bar = 'foo';
    $obj[$bar];
    

    if you can do:

    $obj->{$bar}
    

    or if you can do:

    foreach($obj as $property => $value){}
    

    Or, if you need something a tad more specific, just implement any of the Traversable interfaces.
    And for those rare cases, where you want an object to produce an array from specific properties in a very particular way, just write a method for that and call that method explicitly.

    class ComplexObject
    {
        private $secret = null;
        private $childObject = null;
        public $foo = null;
        //some methods, then:
        public function toArray()
        {//custom array representation of object
            $data = array();
            foreach($this->childObject as $property => $val)
            {
                if (!is_object($this->childObject->{$property}))
                {
                    $data[$property] = $val;
                }
            }
            $data['foo'] = $this->foo;
            return $data;
        }
        //and even:
        public function toJson()
        {
            return json_encode($this->toArray());
        }
    }
    

    Ok, you have to call these methods yourself, explicitly, but that's not that hard, really... is it?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化