1
function my_function() {
    $var1 = "123";
    $var2 = "abc";
    return $var1;
}

Sometimes I want to use $var2 but calling my_function() will simply return what the function returns ( $var1 ).

Is there any trick to retrieve the $var2 data ? maybe my_function($var2) ..

Regards.

3 Answers 3

2

Just pass the arguments by reference, e.g.

$var1 = "";
$var2 = "";

function my_function(&$var1, &$var2) {
                   //^       ^ See here
    $var1 = "123";
    $var2 = "abc";

}

my_function($var1, $var2);
//Now you can use $var1 and $var2 for you next function with the new values.

And if you want to read more about references in general see the manual: http://php.net/manual/en/language.references.php

Sign up to request clarification or add additional context in comments.

1 Comment

Appreciated @Rizier123 :)
1

Another alternative is declaring $var2 as a global inside the function.

$var2 = "hello";
function my_function() {
    global $var2;
    $var1 = "123";
    $var2 = "abc";
    return $var1;
}

Now my_function() will be able to access $var2 declared outside its scope and change its value.

Comments

1
$var1 = '321';
echo $var1; // will be '321' obviously
$myVar = my_function();
function my_function()
{
    $var1 = '123';
    return $var1;
}
echo $var1; // will be '321'
echo $myVar; // will be '123';

Read more: http://php.net/manual/en/language.variables.scope.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.