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-19 11:35:58617browse

In PHP, you can create an object through the new operator and assign it to a variable. At the same time, you can also create an array of objects.

Let’s take a look at how to create a new object array.

First, you need to define a class for creating objects. Below is a simple example class named Person.

class Person{
    public $name;
    public $age;

    public function __construct($name, $age){
        $this->name = $name;
        $this->age = $age;
    }

    public function getDetails(){
        return "Name: " . $this->name . ", Age: " . $this->age;
    }
}

The above code defines a Person class, which has two attributes: $name and $age, and a constructor __construct() for initializing the attributes. It also has a method getDetails(), which returns the details of the Person object.

Next, we can use the following code to create an object array and save multiple Person objects.

$people = array(
    new Person("Alice", 25),
    new Person("Bob", 30),
    new Person("Charlie", 20),
);

foreach($people as $person){
    echo $person->getDetails() . "<br>";
}

The above code uses array syntax to create an object array, which contains three Person objects. Then, use a foreach loop to iterate through the array and call the getDetails() method of each Person object.

If you want to add or remove objects at runtime, you can also use array functions to change the object array. For example, the following code adds a new Person object to the array.

$people[] = new Person("David", 28);

If you want to delete an object in the array, you can use the unset function.

unset($people[2]); //删除Charlie对象

Summary:

In PHP, it is very easy to create an array of objects using the new operator. Just use array syntax to define the elements and initialize each element as an object. Afterwards, array functions or foreach loops can be used to process the array of objects.

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