skip to Main Content

I have a first function that I use to define a variable :

function calculation() {
        return min(0, 150, 30, 20, -8, -200);
}

$mycalculationresult = calculation();

I want to use $mycalculationresult in many other functions.

One way I know is to add, in each function :

function parent_function() {
        global $mycalculationresult;
        // code
}

I read that it’s better to avoid global variables, so I could use this 2nd solution.

function parent_function($mycalculationresult) {  
        // code
        child_function($mycalculationresult);
}
function child_function($mycalculationresult) {
        // code
}

It may be safer (I don’t know) but it’s not practical.

What is the recommended solution?

Is there a way to avoid having to "call/define" $mycalculationresult in each individual function where it’s needed? I know that on WordPress $post_id is defined somewhere in the core files and I don’t have to define it in each function I create.

2

Answers


  1. If you want to use a variable in a function in PHP, and that variable is defined outside the function (and the scenario doesn’t involve classes – for extra info on that see this answer), fundamentally you have two options:

    1. Pass the variable into the function as an input argument:
    function calculation() {
      return min(0, 150, 30, 20, -8, -200);
    }
    
    function anotherFunction($val)
    {
      echo "Received value $val";
    }
    
    $mycalculationresult = calculation();
    anotherFunction($mycalculationresult);
    

    Demo: https://3v4l.org/KTGmJ

    1. Use globals
    function calculation() {
      return min(0, 150, 30, 20, -8, -200);
    }
    
    function anotherFunction()
    {
      global  $mycalculationresult;
      echo "Value is $mycalculationresult";
    }
    
    $mycalculationresult = calculation();
    anotherFunction();
    

    Demo: https://3v4l.org/I2iSa

    These things are always open to interpretation, but in most cases option 1 should be your default choice. It tends to lead to code which is easier to understand, easier to test, and less prone to unexpected bugs – especially in larger codebases. Using globals will work and can occasionally be genuinely helpful, but the potential for unforseen issues when you start to make changes is larger, because the scope of the variable is far less limited or clear.

    Login or Signup to reply.
  2. Security is only part of the reason you don’t want to use too many global variables. Having a variable as an argument to a function also clearly shows you what a function depends upon, and it allow you to more easily reuse the function, which is after all the whole idea behind functions.

    Much PHP code is written using classes. Your wordpress example is probably using this. Objects make it possible to encapsulate variables (= properties) and functions (= methods) at the same time.

    To illustrate this with a mock calculator class, using your example:

    class Calculator
    {
        public $result;
        
        public function __construct($initialResult = 0)
        {
            $this->result = $initialResult;
        }
    
        public function lowestOfTwoValues($value1, $value2) 
        {
            $this->result = min($value1, $value2);
        }
    
        public function lowestOfManyValues($values) 
        {
            foreach ($values as $value) {
                $this->lowestOfTwoValues($this->result, $value);
            }
        }
    
    }
    
    $calculator = new Calculator();
    $calculator->lowestOfManyValues([0, 150, 30, 20, -8, -200]);
    echo $calculator->result;
    

    Demo: https://3v4l.org/3QaZj

    Notice how $result is not used as an argument to each method, it’s a property of the class. You could say it’s a global inside the class.

    This class example is far from perfect, and it only meant to illustrate the point I made above. Can you find the bug?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search