Home » Php » Can a PHP function return a lot of vars?

Can a PHP function return a lot of vars?

Posted by: admin July 12, 2020 Leave a comment


Can a PHP function return a lot of vars without array?

I want like that:


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


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


How can I access to $a,$b,$c vars?

How to&Answers:

Instead of an array, you could use an associative array and cast it to an object, which allows you to access the elements using the -> object syntax:

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;




Create a class that holds your 3 variables and return an instance of the class. Example:

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;

Of course the last 3 lines are not particularly efficient because a() gets called 3 times. A sensible refactoring would result in those 3 lines being changed to:

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


If you want to access those variables that way (without using an array), you should better use a class:

class Name{
    var $a = "a";
    var $b = "b";

$obj = new Name();
echo $obj->a;


You could build a class and return an object instead. Check out this SO answer for something that you might find useful.


Yes this is possible when the return variable has to be as an array or it should be long string with multiple values separated with any of the delimiters like “, | #” and so on.

if it is built as an array we can receive it using var_dump function available in PHP

see below code



PHP Manual > Returning values:

A function can not return multiple values, but similar results can be obtained by returning an array.

function small_numbers()
    return array (0, 1, 2);
list ($zero, $one, $two) = small_numbers();

no need for classes here.