开发者

Programming Practices: Typecasting array to object

开发者 https://www.devze.com 2023-02-08 14:40 出处:网络
I just read about Top Bad Practices in PHP and became 开发者_开发百科curious if what I\'m doing is also a bad practice...

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!


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();


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消