0

So I just started learning about OOP and I found this problem about how params works.

I thought that when I executed t his code, I'll get 5 as result:

class First {
    protected $var = 10;
    public function setVar(int $var) {
        $this -> var = $var;
    }

    public function __toString() {
        return (string)$this->var;
    }
}

class Second {
    protected $x;
    public function __construct(First $x) {
        $this -> x = $x;
    }
    public function setVar(int $var) {
        $this -> x -> setVar ($var);
    }
}

$x = null;
$x = new First();
$x -> setVar(5);

$y = new Second($x);
$y->setVar(15);

echo $x;

But it doesn't work like that. I get 15 and I'm curious why. I saw that if I remove this specific line, $this -> x -> setVar ($var);, I get the result I was expecting. So I think that my problem is because I don't understand how this line works. Maybe you can help me. Thank you!

  • 2
    Basically when you pass in $x to the Second class, you're passing a reference to it, not making a copy of it. So if you modify the version held in $y, you're also modifying the original $x because they actually point to the same location in memory. – ADyson Jul 29 '21 at 09:46
  • 1
    Does this answer your question? [Are PHP Variables passed by value or by reference?](https://stackoverflow.com/questions/879/are-php-variables-passed-by-value-or-by-reference) - see the answers about objects specifically (value types are treated differently). – ADyson Jul 29 '21 at 09:47
  • Yes! I took a look on "Are PHP Variables passed by value or by reference?" and now makes sense to me. Thank you again! – Phunkzilla14 Jul 29 '21 at 15:28

0 Answers0