0

My variables are not working, and I'm not sure why. I did not define $var as static, so when I reference it as global, or as $this->var, it should be the same variable, right? Except it isn't.

Some people say 'global' shouldn't be used, instead pass parameters to the function. But what if I need to work with 20 variables in an instance's function? Do I really pass 20 parameters to it? Doesn't it become unreadable and unclear?

I'm running PHP 7.2.8. on XAMPP, but that isn't really relevant.

<?php
class Test{

    public $var;
    public function __construct($param)//1
    {
        global $var; //5
        $this->var = $param; //1
        $var = $param * 5; //5
    }

    public function wtf(){
        global $var; //5
        $foo = $this->var; //1

        echo "var: $var <br>";
        echo "this var: $foo <br>";
    }
}

$foo = new Test(1);
$foo->wtf();
$value = $foo->var;
echo "Value: $value";
?>

Output:

var: 5
this var: 1
Value: 1

I'm expecting the $var to be the same thing in both cases. Why does it become two?

  • 1
    If I am reading correctly, you are expecting the `global` keyword to reference the same variable `$this->var` and `$var` ? That is not the case. The `public $var` will always be local to the class even if you reference a separate `global $var`, which could also be called `$GLOBALS['var']` - this is a source of naming confusion I would want to avoid. – Michael Berkowski May 05 '19 at 11:53
  • I'll search the site a bit for an existing set of answers that addresses parts of this... e.g: https://stackoverflow.com/a/12446305/541091 – Michael Berkowski May 05 '19 at 11:55
  • 1
    Some of the answers here address the issue of passing loads of parameters to the constructor by creating an OptionsContainer object to inject. https://stackoverflow.com/questions/5967332/php-best-way-to-initialize-an-object-with-a-large-number-of-parameters-and-def – Michael Berkowski May 05 '19 at 12:01
  • `$var` and `$this->var` both are the different variable.`$var` A global variable, which can be accessed anywhere`$this->var` is the variable of class Test, which has public access and can be modified inside the class – Rakesh Jakhar May 05 '19 at 12:11
  • @RakeshJakhar So `public $var` is not a variable of the instance of the class Test? – David Frau May 05 '19 at 12:31
  • @DavidFrau public $var is an instance of class Test, whereas global $var is a global variable – Rakesh Jakhar May 05 '19 at 12:32

0 Answers0