编程实践:将数组类型转换为对象

发布于 2024-10-16 05:09:05 字数 404 浏览 1 评论 0原文

我刚刚读到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夢归不見 2024-10-23 05:09:05

不,这不是坏习惯。事实上,它甚至在 PHP 页面上作为已发布的示例:http://www.php.net/manual/en/language.types.object.php#language.types.object.casting

还有很多合法的用途(你的例子有点反复无常);例如:

$result = (object)mysql_fetch_assoc();

$result = mysql_fetch_object();

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:

$result = (object)mysql_fetch_assoc();

is faster than

$result = mysql_fetch_object();
你穿错了嫁妆 2024-10-23 05:09:05

好吧,虽然这不适用于您已经报告的多维数组,但这并不是一个坏习惯。

但是您应该注意很多情况,例如 thisthis 报告数组比对象快一点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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文