Home » Php » Get variables from the outside, inside a function in PHP

Get variables from the outside, inside a function in PHP

Posted by: admin April 23, 2020 Leave a comment

Questions:

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.

How to&Answers:

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?
}

Answer:

Globals will do the trick but are generally good to stay away from. In larger programs you can’t be certain of there behaviour because they can be changed anywhere in the entire program. And testing code that uses globals becomes very hard.

An alternative is to use a class.

class Counter {
    private $var = 1;

    public function increment() {
        $this->var++;
        return $this->var;
    }
}

$counter = new Counter();
$newvalue = $counter->increment();

Answer:

$var = 1;

function() {
  global $var;

  $var += 1;
  return $var;
}

OR

$var = 1;

function() {
  $GLOBALS['var'] += 1;
  return $GLOBALS['var'];
}

Answer:

$var = '1';
function addOne() use($var) {
   return $var + 1;
}

Answer:

See http://php.net/manual/en/language.variables.scope.php for documentation. I think in your specific case you weren’t getting results you want because you aren’t assigning the $var + 1 operation to anything. The math is performed, and then thrown away, essentially. See below for a working example:

$var = '1';

function addOne() {
   global $var;
   $var = $var + 1;
   return $var;
}

Answer:

This line in your function:
$var + 1
will not change the value assigned to $var, even if you use the global keyword.

Either of these will work, however:
$var = $var + 1;
or
$var += 1;

Answer:

<?php
$var = '1';
function x ($var) {
return $var + 1;
}
echo x($var); //2
?>