Home  >  Article  >  Backend Development  >  How to create a new object array in php

How to create a new object array in php

PHPz
PHPzOriginal
2023-04-17 14:58:15691browse

In PHP, creating an array of objects is very simple. You can use the following two methods to accomplish this task.

Method 1: Use a simple class constructor

Step 1. Create a simple class to create an object array. This class can have multiple properties and methods.

class Person{
    public $name;
    public $age;
    public $gender;
}

Step 2. Use the constructor of this class to create an object array.

$person1 = new Person();
$person1->name = "张三";
$person1->age = 18;
$person1->gender = "男";

$person2 = new Person();
$person2->name = "李四";
$person2->age = 22;
$person2->gender = "女";

$person3 = new Person();
$person3->name = "王五";
$person3->age = 25;
$person3->gender = "男";

$personArray = array($person1, $person2, $person3);

The above code will create an object array containing three different objects.

Method 2: Using array elements

Step 1. Follow the method described above to create a simple class, and then use the array elements when creating an object array.

$person1 = array('name'=>'张三', 'age'=>18, 'gender'=>'男');
$person2 = array('name'=>'李四', 'age'=>22, 'gender'=>'女');
$person3 = array('name'=>'王五', 'age'=>25, 'gender'=>'男');

$personArray = array($person1, $person2, $person3);

The above code will create an object array containing three different objects.

Summary

The above are two methods of creating object arrays in PHP. Either way, care needs to be taken to create limits on the amount of code to ensure performance.

The above is the detailed content of How to create a new object array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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