Henrikz Henrikz - 1 year ago 38
PHP Question

Get variables from the outside, inside a function in PHP

I'm trying to figure out how i can use a variable, that has been set outside a function, inside. Is there any way of doing this? I've tried to set the variable to "global" but it doesn't seems to work out as expected.

A simple example of my code

$var = '1';

function() {
$var + 1;
return $var;

i want this, to return the value of 2.


You'll need to use the global keyword inside your function. http://php.net/manual/en/language.variables.scope.php

EDIT (embarrassed I overlooked this, thanks to the commenters)

...and store the result somewhere

$var = '1';
function() {
    global $var;
    $var += 1;   //are you sure you want to both change the value of $var
    return $var; //and return the value?