Casting an Array with Numeric Keys as an Object

后端 未结 4 1268
余生分开走
余生分开走 2020-11-27 07:23

I was poking around PHPs casting mechanism, and ran into an odd case when casting an array as an object

$o = (object) array(\'1\'=>\'/foo/bar\');   
$o =          


        
4条回答
  •  爱一瞬间的悲伤
    2020-11-27 08:08

    I think you get an error because casting an integer key of an array to an object / subobject will break the naming conventions of PHP varibles.

    Tips:

    • Decide before hands whether you want to have an OBJECT or an ARRAY
    • Be careful with type casting (e.g. (object) array(1=>'string') do not do such things)
    • Use castings for validation and not to convert things
    • Avoid using objects as "fake" arrays

提交回复
热议问题