I am trying to set three variables from a test function.
Here's my code so far:
function test()
{
$x = 1;
$y = 2;
$z = 3;
}
test();
# should print '1', '2', and '3'
echo $x;
echo $y;
echo $z;
I am trying to set three variables from a test function.
Here's my code so far:
function test()
{
$x = 1;
$y = 2;
$z = 3;
}
test();
# should print '1', '2', and '3'
echo $x;
echo $y;
echo $z;
Just return an object or an array (array is probably the way to go):
function test(){
$data = array(
'x' => 1,
'y' => 2,
'z' => 3
);
return $data;
}
print_r( test() );
or call each value:
echo $data['x'];
...
There'd be 3 easy-to-apply options in this case. One would be to pass the variables by reference, in stead of by value. The other would be to return an array. Another option would be to use global variables.
Here's an example of both:
<?php
function example (&$x, &$y, &$z)
{
$x = 1;
$y = 2;
$z = 3;
}
?>
Passing a variable by reference means that you're passing the actual variable (the space allocated for it in the computer's memory), in stead of by value (just passing the value to the function) as usual.
So when you pass a variable by reference (which the & character does), and you manipulate the value, the value of the original variable gets changed as well.
<?php
function example ($x, $y, $z)
{
$arr['x'] = 1;
$arr['y'] = 2;
$arr['z'] = 3;
return $arr;
}
?>
Now you can access the values by using $arr['x'];, $arr['y']; and $arr['z'];.
<?php
$x = 0;
$y = 0;
$z = 0;
function example ()
{
global $x, $y, $z;
$x = 1;
$y = 2;
$z = 3;
}
?>
options:
use references:
function test(&$x, &$y, &$z) {
$x = 1;
$y = 2;
$z = 3;
}
or return an array and use extract:
function test() {
return array(
'x' => 1,
'y' => 2,
'z' => 3
);
}
extract(test());
Define the variables as global? Like:
function test()
{
global $x, $y, $z;
$x = 1;
$y = 2;
$z = 3;
}
Example #1 Using global so I suggest that you notify the php.net team about their poor programming too...