-1

Possible Duplicate:
PHP: Global variable scope

How can I set a variable outside a function from inside the function? Here is what I mean:

$myVar = false;

function myFunction($param1 $param2){
    ....
    if($param1 == $x){
        $myVar = $param1;
    }
}

$myVar seems to always stay empty. How can I do this?

Thank you!

0

1 Answer 1

1

You create a new local variable called `myVar'.

If you would like to stick with your variable outside of the function, you can use the following code to get it working, but global variables are at least in my opinion not the best solution in general.

$myVar = false;

function myFunction($param1 $param2){
    ....
    global $myVar;
    if($param1 == $x){
        $myVar = $param1;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, What would be a better solution then?
It depends on what you want to achieve and couldn't be answered in this general case. A possible starting point could be to use an additional parameter to get myVar inside your function. Then you can use your exisiting code for the moment but have the possibility to design it better afterwards. For the additional parameter, you need to pass it by reference - see here: php.net/manual/en/language.references.pass.php

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.