PHP函数可以返回很多变量吗?

sun*_*tch 7 php

PHP函数可以返回很多没有数组的变量吗?

我想这样:

<?php

public function a()
{
   $a = "a";
   $b = "b";
   $c = "c";

}

echo a()->a;
echo a()->b;
echo a()->c;

?>
Run Code Online (Sandbox Code Playgroud)

如何访问$ a,$ b,$ c变量?

Hei*_*nzi 8

您可以使用关联数组并将其强制转换为对象,而不是数组,这允许您使用->对象语法访问元素:

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;
Run Code Online (Sandbox Code Playgroud)


Ste*_*rig 6

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;
Run Code Online (Sandbox Code Playgroud)