Can a PHP function return a lot of vars?

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

I want like this:

<?php public function a() { $a = "a"; $b = "b"; $c = "c"; } echo a()->a; echo a()->b; echo a()->c; ?> 

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

+7
php
source share
8 answers

Instead of an array, you can use an associative array and pass it to an object that allows you to access 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; 
+8
source share
 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; 
+6
source share
+3
source share

Create a class containing your 3 variables and returning an instance of the class. Example:

 <?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; ?> 

Of course, the last 3 lines are not particularly efficient, because a() is called 3 times. Reasonable refactoring will result in these 3 lines being changed to:

 $a = a(); echo $a->a; echo $a->b; echo $a->c; 
+3
source share

If you want to access these variables this way ( without using an array ), you better use a class:

 class Name{ var $a = "a"; var $b = "b"; } $obj = new Name(); echo $obj->a; 
+2
source share

You can create a class and return an object instead. Check out this SO answer for what you might find useful.

+2
source share

Yes, it is possible when the returned variable should be like an array or should be a long string with several values โ€‹โ€‹shared with any delimiters like ", | #", etc.

if it is built as an array, we can get it using the var_dump function available in PHP

see below code

var_dump($array);

+1
source share

PHP Guide> Return Values :

A function cannot 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(); 

no need for classes here.

+1
source share

All Articles