_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 magictoArray
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 Matlab怎么求解含参的二重积分?
- ¥15 苹果手机突然连不上wifi了?
- ¥15 cgictest.cgi文件无法访问
- ¥20 删除和修改功能无法调用
- ¥15 kafka topic 所有分副本数修改
- ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
- ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
- ¥40 串口调试助手打开串口后,keil5的代码就停止了
- ¥15 电脑最近经常蓝屏,求大家看看哪的问题
- ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档