PHP arrays can store objects. Because PHP is a programming language with weak data types, arrays in PHP can store any number of data of any type, that is, there is no limit on the type of array elements, which can be numbers, strings, Boolean values, arrays, Object objects, etc. .
The operating environment of this tutorial: Windows 10 system, PHP8.1.3 version, Dell G3 computer.
Array is one of the most important data types in PHP and is widely used in PHP. Because PHP is a programming language with weak data types, array variables in PHP can store any number of data of any type, and can implement the functions of data structures such as heaps, stacks, and queues in other strong data types.
Simply put, there is no restriction on the type of PHP array elements, which can be numbers, strings, Boolean values, arrays, Object objects, etc.
Example 1:
<?php header("Content-type:text/html;charset=utf-8"); $arr= array(1,2,"3",4,"hello",TRUE); var_dump($arr); ?>
Example 2:
<?php header("Content-type:text/html;charset=utf-8"); $array = array ( array("张三",25,"男"), array("李四",21,"男"), array("娜娜",22,"女") ); var_dump($array); ?>
If the elements in an array is another array, which constitutes an array containing arrays, that is, a multi-dimensional array:
Two-dimensional array
Three-dimensional array
Four-dimensional array
. ....
However, when the array exceeds three dimensions, its readability will be greatly reduced, and it will also be inconvenient to manage.
Example 3:
<?php header('content-type:text/html;charset=utf-8'); class foo{ function do_foo(){ echo "Doing foo."; } } $bar = new foo; $arry1=array(1,$bar);//这里将实例化的对象存入数组 var_dump($arry1);//这里打印数组结构 你会发现下标1的位置存储了一个object对象 $arry1[1]->do_foo();//以数组形式 调用do_foo(); $bar->do_foo();//正常的调用do_foo() //两种方式输出是一样的 充分说明 数组是可以存储对象的 ?>
The above is the detailed content of Can php arrays store objects?. For more information, please follow other related articles on the PHP Chinese website!