Structs data type in php?

后端 未结 7 1437
悲哀的现实
悲哀的现实 2020-12-07 17:47

Can anyone give me example for structs data type in php ? How come there is something like structs in php all of a sudden ?

7条回答
  •  自闭症患者
    2020-12-07 18:01

    I cobbled together a 'dynamic' struct class today, had a look tonight and someone has written something similar with better handling of constructor parameters, it might be worth a look:

    http://code.activestate.com/recipes/577160-php-struct-port/

    One of the comments on this page mentions an interesting thing in PHP - apparently you're able to cast an array as an object, which lets you refer to array elements using the arrow notation, as you would with a Struct pointer in C. The comment's example was as follows:

    $z = array('foo' => 1, 'bar' => true, 'baz' => array(1,2,3));
    //accessing values as properties
    $y = (object)$z;
    echo $y->foo;
    

    I haven't tried this myself yet, but it may be that you could get the desired notation by just casting - if that's all you're after. These are of course 'dynamic' data structures, just syntactic sugar for accessing key/value pairs in a hash.

    If you're actually looking for something more statically typed, then ASpencer's answer is the droid you're looking for (as Obi-Wan might say.)

提交回复
热议问题