Can a PHP function return a lot of vars without array?
I want like that:
<?php
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?
A function is not restricted to return a variable, it can return zero, one, two or more values.
You can return multiple values from a function using either a dictionary, a tuple, or a list. These data types all let you store multiple values. There is no specific syntax for returning multiple values, but these methods act as a good substitute.
Given a list of items and the task is to retrieve the multiple selected value from a select box using PHP. Use multiple attribute in HTML to select multiple value from drop down list. Selecting multiple values in HTML depends on operating system and browser.
A return value can be any one of the four variable types: handle, integer, object, or string. The type of value your function returns depends largely on the task it performs.
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;
http://php.net/manual/en/function.list.php
Create a class that holds your 3 variables and return 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()
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With