Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structs data type in php?

Tags:

php

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

like image 407
ktm Avatar asked Oct 05 '10 06:10

ktm


People also ask

What is struct data type?

A structure is a collection of one or more variables, possibly of different types, grouped under a single name. It is a user-defined data type. They help to organize complicated data in large programs, as they allow a group of logically related variables to be treated as one.

Can structs have strings?

The answer is yes unless you are using an obsolete compiler that does not support initialization of structures with string class members. Make sure that the structure definition has access to the std namespace. You can do this by moving the using directive so that it is above the structure definition.

Can structs contain different data types?

A struct is also a collection of data items, except with a struct the data items can have different data types, and the individual fields within the struct are accessed by name instead of an integer index.


2 Answers

Closest you'd get to a struct is an object with all members public.

class MyStruct {     public $foo;     public $bar; }  $obj = new MyStruct(); $obj->foo = 'Hello'; $obj->bar = 'World'; 

I'd say looking at the PHP Class Documentation would be worth it. If you need a one-off struct, use the StdObject as mentioned in alex's answer.

like image 54
ASpencer Avatar answered Sep 20 '22 05:09

ASpencer


You can use an array

$something = array(    'key' => 'value',    'key2' => 'value2' ); 

or with standard object.

$something = new StdClass();  $something->key = 'value'; $something->key2 = 'value2'; 
like image 44
alex Avatar answered Sep 22 '22 05:09

alex