Can php arrays store objects?

小老鼠
Release: 2023-06-28 17:04:12
Original
824 people have browsed it

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. .

Can php arrays store objects?

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);
?>
Copy after login

Can php arrays store objects?

Example 2:

<?php
header("Content-type:text/html;charset=utf-8");
$array = array
(
    array("张三",25,"男"),
    array("李四",21,"男"),
    array("娜娜",22,"女")
);
var_dump($array);
?>
Copy after login

Can php arrays store objects?

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(&#39;content-type:text/html;charset=utf-8&#39;);  
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()
//两种方式输出是一样的 充分说明 数组是可以存储对象的
?>
Copy after login

Can php arrays store objects?

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!