简体   繁体   English

如何摆脱PHP中的数组/对象转换?

[英]How to get rid of array/object casting in PHP?

Some methods/functions only accept/return arrays, others only get/give objects. 一些方法/函数仅接受/返回数组,另一些仅获取/提供对象。 In my day to day PHP programming I have to repetitively convert objects to array and vice versa. 在日常的PHP编程中,我必须反复将对象转换为数组,反之亦然。 ( (object) ['x'=>3] and (array) (new stdClsss()) ). (object) ['x'=>3](array) (new stdClsss()) )。

Most classes do not implement ArrayAccess . 大多数类不实现ArrayAccess Smartly in JavaScript, these two syntaxes are interchangeable. 在JavaScript中,这两种语法很聪明,可以互换。 Is there any hack, workaround to stick to one of them and get rid of variable casting and "Cannot use object of type xxx as array in " or "Cannot use object of type stdClass as arhray in "Cannot access property on non-object" messages. 是否有任何破解,变通方法来坚持其中之一并摆脱变量强制转换,并且“不能在非对象上访问属性”中的“不能将xxx类型的对象用作数组”或“不能将stdClass类型的对象用作arhray”消息。

I came up with ary . 我想到了阿里

$var= ary(['x' => 'foo', 'y' => 'bar']);
$foo = $var->x; //or
$foo = $var['x'];

Try using php serializing function, instead of trying to convert them. 尝试使用php序列化功能,而不是尝试转换它们。

$array = array();
$obj = serialize($array);
$again = unserialize($obj);

This will help you if your interchange is about to save datum. 如果您的互换将要保存基准,这将为您提供帮助。

if, working with the object is your bulk task, try to define a class library for your object and then, implement your function like ToArray() , ToString() , ToObject() or ToStorable() , instead of converting them in your code with natural functions. 如果使用该对象是您的批量任务,请尝试为该对象定义一个类库,然后实现ToArray()ToString()ToObject()ToStorable() ,而不是在代码中进行转换具有自然功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM