Php class init array

ArrayObject::__construct

Параметр array принимает значение типа array или Object .

Флаги для управления поведением объекта ArrayObject . Смотрите ArrayObject::setFlags() .

Указывает класс, который будет использоваться в качестве итератора объекта ArrayObject . Класс должен реализовать интерфейс ArrayIterator .

Примеры

Пример #1 Пример использования ArrayObject::__construct()

$arrayobject = new ArrayObject ( $array );

Результат выполнения данного примера:

object(ArrayObject)#1 (3) < [1]=>string(3) "one" [2]=> string(3) "two" [3]=> string(5) "three" >

Смотрите также

User Contributed Notes 4 notes

BTW, if you need to change array later, use exchangeArray() method. Good to know when you are writing a class that extends ArrayObject()

AFAIK, exchangeArray() doesn’t return anything.

$a = array( ‘one’ , ‘two’ , ‘three’ );
$ao = new ArrayObject ( $a );

foreach ( $ao as $element ) echo $element . ‘ ‘ ; // one two three
>

$b = array( ‘four’ , ‘five’ , ‘six’ );
$ao -> exchangeArray ( $b ); // returns null

foreach ( $ao as $element ) echo $element . ‘ ‘ ; // four five six
>
?>

The great confusion with this class is in its naming. ArrayObject infers it will behave as an Array and as an Object. It won’t. It behaves as an array. It would better be called ArrayType. You can, with some work, get it to work both as an object and as an array, but that is up to you.

As Marcus explained, the flag ArrayObject::SPL_ARRAY_AS_PROPS means the array element may be used as a property if there is no conflict with visible properties.

If there are visible properties in the class, the array element will not overwrite it’s value.

class Rules extends ArrayObject <
public $len = 1 ;
function __construct ( $array ) <
parent :: __construct ( $array , ArrayObject :: ARRAY_AS_PROPS );
$this [ ‘len’ ] = 2 ;
>
>
$x = new Rules (array( 1 , 2 ));
echo $x -> len ;
?>
Result: 1

class Rules extends ArrayObject <
private $len = 1 ;
function __construct ( $array ) <
parent :: __construct ( $array , ArrayObject :: ARRAY_AS_PROPS );
$this [ ‘len’ ] = 2 ;
>
>
$x = new Rules (array( 1 , 2 ));
echo $x -> len ;
?>
Result: 2

Note that the first argument to ArrayObject::__construct, the initial array, is passed by reference. Nevertheless, modification of the array doesn’t modify the object, so it may cause unexpected behaviour.

$array = array( ‘foo’ => ‘initial’ );
$obj = new ArrayObject ( $array );

// array was passed by reference:
$obj [ ‘foo’ ] = ‘modified’ ;
var_dump ( $array ); // foo => modified

// but it doesn’t work backwards:
$array [ ‘foo’ ] = ‘modified_again’ ;
var_dump ( $obj ); // foo => modified
var_dump ( $array ); // foo => modified_again
?>

Источник

Create Array of Objects in PHP

Create Array of Objects in PHP

  1. Create an Array of Class’ Objects in PHP
  2. Create an Array of stdClass Objects in PHP
  3. Create an Array of Object Using the array() Function in PHP
Читайте также:  Не работает слайдер html

This article will introduce methods to create an array of objects in PHP.

Create an Array of Class’ Objects in PHP

We can use the array() function to create an array of objects in PHP. The function will take the object as the arguments and will create an array of those objects. We can create objects by creating a class and defining some properties of the class. The properties of the class will have some values. Finally, the properties and values will form a key-value pair in the array.

For example, create a class Motorcycle . Create two public properties, $name and $type . Then create an object $bike1 of the Motorcycle class using the new keyword. Populate the properties of the object with any suitable values. Similarly, create another object, $bike2 and populate the values accordingly. Next, create a variable $bike and write the array() function to it with the two objects $bike1 and $bike2 as the parameters. Finally, print the array variable $bikes with the print_r() function.

Thus, we can create an array of objects, as shown in the output section. We have created an array of the Motorcycle objects in the example below. We can see the indexes 0 and 1 for each Motorcycle object. The properties and values of each object are formed as a key-value pair, as stated above.

php class Motorcycle   public $name;  public $type; >  $bike1 = new Motorcycle(); $bike1->name = 'Husqvarna'; $bike1->type = 'dirt'; $bike2 = new Motorcycle(); $bike2->name = 'Goldwing'; $bike2->type = 'touring'; $bikes = array($bike1, $bike2); ?>  
Array (  [0] => Motorcycle Object  (  [name] => Husqvarna  [type] => dirt  )   [1] => Motorcycle Object  (  [name] => Goldwing  [type] => touring  ) ) 

Create an Array of stdClass Objects in PHP

We can create an array of objects by creating an object of the stdClass in PHP. The stdClass is defined in the standard set of functions in PHP. It is not a base class of objects; rather, it is an empty class that can be used to typecast and set dynamic properties. We can create an object of the stdClass , which is an array by nature. Then, we can assign the dynamic properties to the object with the indexes.

For example, create an array $bikes[] and make it an object of the stdClass using the new keyword. Then, give the index 0 to the $bikes[] array and assign the properties name and type . Give some suitable values of your choice to the properties. Repeat the same process for index 1 in the $bikes[] array. Next, print the $bikes array.

The example below creates an array of stdClass objects, as shown in the output section below.

php $bikes[] = new stdClass;  $bikes[0]->name = 'Husqvarna'; $bikes[0]->type = 'dirt';  $bikes[1]->name = 'Goldwing'; $bikes[1]->type = 'touring'; ?>  
Array (  [0] => stdClass Object  (  [name] => Husqvarna  [type] => dirt  )   [1] => stdClass Object  (  [name] => Goldwing  [type] => touring  )  ) 

Create an Array of Object Using the array() Function in PHP

This method is quite similar to the first method. We can create an array of objects by creating objects from a class. Here, we will first create an array using the array() function and then populate the objects in the array. In the first method, we created objects and then populated them in the array using the array() function. We will use the array index to set the values to the properties.

For example, create a Motorcycle class with properties as in the first method. Then create an array with the $bikes variable using the array() function. Leave the array empty. Then, create an object of the class from the $bike array using the 0 index. Set the properties and values for the 0 index as well. Repeat the same process for the 1 index. Finally, print the array using the print_r() function.

php class Motorcycle   public $name;  public $type; > $bikes = array();  $bikes[0] = new Motorcycle(); $bikes[0]->name = 'Husqvarna'; $bikes[0]->type = 'dirt';  $bikes[1] = new Motorcycle(); $bikes[1]->name = 'Goldwing'; $bikes[1]->type = 'touring'; ?>  
Array (  [0] => Motorcycle Object  (  [name] => Husqvarna  [type] => dirt  )   [1] => Motorcycle Object  (  [name] => Goldwing  [type] => touring  )  ) 

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

Related Article — PHP Array

Related Article — PHP Object

Copyright © 2023. All right reserved

Источник

Php class init array

// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4

Used to creating arrays like this in Perl?

Looks like we need the range() function in PHP:

$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>

You don’t need to array_merge if it’s just one range:

There is another kind of array (php>= 5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]

when getting the keyed data with

php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).

When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:

$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23

but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :

$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2

This function makes (assoc.) array creation much easier:

function arr (. $array )< return $array ; >
?>

It allows for short syntax like:

$arr = arr ( x : 1 , y : 2 , z : 3 );
?>

Instead of:

$arr = [ «x» => 1 , «y» => 2 , «z» => 3 ];
// or
$arr2 = array( «x» => 1 , «y» => 2 , «z» => 3 );
?>

Sadly PHP 8.2 doesn’t support this named arguments in the «array» function/language construct.

Источник

Оцените статью