PHP method analysis: How to output two values?

王林
Release: 2024-03-22 17:40:02
Original
493 people have browsed it

PHP method analysis: How to output two values?

PHP method analysis: How to output two values?

In PHP, sometimes we need to output multiple values from a method. In this case, we can use arrays, objects, or reference passing to achieve this. Three methods to output two values will be introduced below.

Method 1: Return an array

function getTwoValues(){ $value1 = 10; $value2 = 20; return [$value1, $value2]; } list($result1, $result2) = getTwoValues(); echo $result1; // 输出 10 echo $result2; // 输出 20
Copy after login

Method 2: Return an object

class TwoValues{ public $value1; public $value2; function __construct($v1, $v2){ $this->value1 = $v1; $this->value2 = $v2; } } function getTwoValues(){ $value1 = 10; $value2 = 20; return new TwoValues($value1, $value2); } $result = getTwoValues(); echo $result->value1; // 输出 10 echo $result->value2; // 输出 20
Copy after login

Method 3: Pass by reference

function getTwoValues(&$value1, &$value2){ $value1 = 10; $value2 = 20; } getTwoValues($result1, $result2); echo $result1; // 输出 10 echo $result2; // 输出 20
Copy after login

Whether using array, Whether passed by object or reference, it is easy to output two values. Which method to choose depends on the actual needs. I hope the above methods can be helpful to you.

The above is the detailed content of PHP method analysis: How to output two values?. 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
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!