PHP functions can return arrays, objects or class instances: 1. Array: use square brackets; 2. Object: use the new keyword to create an object; 3. Class instance: omit the new keyword. Practical case: getUsers() returns an array of users, and createUser() creates a user object.
PHP function return value type: array, object, class instance
PHP function can return various types of values, including Instances of arrays, objects, and classes.
Array
To return an array as a function return value, use square brackets:
<?php function getArray(): array { return [1, 2, 3]; } ?>
Object
To return an object, create the object using the new keyword as follows:
<?php class Person { private $name; public function __construct(string $name) { $this->name = $name; } public function getName(): string { return $this->name; } } function getObject(): Person { return new Person('John Doe'); } ?>
Instance of class
Returning an instance of a class is similar to returning an object , but you can omit the new keyword, as shown below:
<?php class Animal { private $species; public function __construct(string $species) { $this->species = $species; } public function getSpecies(): string { return $this->species; } } function getInstance(): Animal { return Animal('Dog'); } ?>
Practical case
Suppose you have a function to obtain the detailed information of a batch of users:
function getUsers(): array { // ... 数据库查询,返回用户数组 }
To use this function in a controller you would:
<?php $users = getUsers(); // 遍历用户数组 foreach ($users as $user) { // ... } ?>
Similarly, if you have a function that creates a new user object:
function createUser(string $name, string $email): Person { // ... 数据库查询,返回新的用户对象 }
To use it in Using this function in your model you can:
<?php $user = createUser('John Doe', 'john.doe@example.com'); // 访问用户属性 echo $user->getName(); // 输出:John Doe ?>
The above is the detailed content of Can the type of the return value of a PHP function be an array, object, or instance of a class?. For more information, please follow other related articles on the PHP Chinese website!