一个 PHP 函数能否在不使用数组的情况下返回多个变量?
我想要这样:
<?php
public function a()
{
$a = "a";
$b = "b";
$c = "c";
}
echo a()->a;
echo a()->b;
echo a()->c;
?>
如何访问 $a,$b,$c 变量?
一个 PHP 函数能否在不使用数组的情况下返回多个变量?
我想要这样:
<?php
public function a()
{
$a = "a";
$b = "b";
$c = "c";
}
echo a()->a;
echo a()->b;
echo a()->c;
?>
如何访问 $a,$b,$c 变量?
你可以使用关联数组并将其转换为对象,而不是使用普通数组,这样你就可以使用->
对象语法访问元素:
function a()
{
return (object) array(
'a' => "a",
'b' => "b",
'c' => "c");
}
echo a()->a; // be aware that you are calling a() three times here
echo a()->b;
echo a()->c;
function a1() {
return array(
'a' => 'a',
'b' => 'b',
'c' => 'c'
);
}
$a1 = a1();
echo $a1['a'];
echo $a1['b'];
echo $a1['c'];
function a2() {
$result = new stdClass();
$result->a = "a";
$result->b = "b";
$result->c = "c";
return $result;
}
$a2 = a2();
echo $a2->a;
echo $a2->b;
echo $a2->c;
// or - but that'll result in three function calls! So I don't think you really want this.
echo a2()->a;
echo a2()->b;
echo a2()->c;
<?php
class A {
public $a;
public $b;
public $c;
public function __construct($a, $b, $c) {
$this->a = $a;
$this->b = $b;
$this->c = $c;
}
}
function a() {
return new A("a", "b", "c");
}
echo a()->a;
echo a()->b;
echo a()->c;
?>
当然,最后三行并不是特别高效,因为a()
被调用了三次。一个明智的重构将导致这三行代码被更改为:
$a = a();
echo $a->a;
echo $a->b;
echo $a->c;
class Name{
var $a = "a";
var $b = "b";
}
$obj = new Name();
echo $obj->a;
A function can not return multiple values, but similar results can be obtained by returning an array.
<?php function small_numbers() { return array (0, 1, 2); } list ($zero, $one, $two) = small_numbers();
这里不需要类。
当返回变量必须是数组或长字符串,其中包含多个值,用任何分隔符(如“,|#”等)分隔时,这是可能的。
如果它被构建为数组,我们可以使用PHP中可用的var_dump函数接收它。
请参见下面的代码
var_dump($array);
var $a = "a"
,或者更好地使用显式可见性关键字:public $a = 'a'
,protected $a = 'a'
或private $a = 'a'
。 - Igor Zinov'yev