Home > Article > Backend Development > 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.
function getTwoValues(){ $value1 = 10; $value2 = 20; return [$value1, $value2]; } list($result1, $result2) = getTwoValues(); echo $result1; // 输出 10 echo $result2; // 输出 20
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
function getTwoValues(&$value1, &$value2){ $value1 = 10; $value2 = 20; } getTwoValues($result1, $result2); echo $result1; // 输出 10 echo $result2; // 输出 20
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!