编程实践:将数组类型转换为对象
我刚刚读到 PHP 中最糟糕的实践 并开始好奇我正在做的事情是否也是一个糟糕的做法练习...
我通常将数组类型转换为对象,
$person = (object)$person;
只是因为我更喜欢打字
$person->name
而不是
$person['name']
注意:当我使用这种方法时,我不处理多维数组。
需要专家的建议,这样如果这是一种不好的做法,我就可以停止:(谢谢大家!
I just read about
Top Bad Practices in PHP and became curious if what I'm doing is also a bad practice...
I usually typecast an array to object
$person = (object)$person;
just because I prefer typing
$person->name
than
$person['name']
Note: I'm not dealing with multi-dimensional arrays when I use this approach.
Need expert advice so I can stop if this is a bad practice :( Thanks Guys!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这不是坏习惯。事实上,它甚至在 PHP 页面上作为已发布的示例:http://www.php.net/manual/en/language.types.object.php#language.types.object.casting
还有很多合法的用途(你的例子有点反复无常);例如:
比
No, it's not bad practice. As a matter of fact, it's even on the PHP page as a published example: http://www.php.net/manual/en/language.types.object.php#language.types.object.casting
There are plenty of legitimate uses, also (your example is a bit capricious); for example:
is faster than
好吧,虽然这不适用于您已经报告的多维数组,但这并不是一个坏习惯。
但是您应该注意很多情况,例如 this 和 this 报告数组比对象快一点PHP5,PHP4 的速度要快得多。在进行大量迭代时请记住这一点。
Well, while this does not work with multidimensional arrays as already reported by you, it's not a bad practice.
However you should note that a lot of cases, like this and this reports that arrays are a bit faster than objects in PHP5, very much faster in PHP4. Keep this in mind while making a huge number of iterations.