0

I have a problem when I pass data through from one function to a class that it is updating the data that I am passing in the origination class in even though I am not doing it by reference.

<?php
namespace core\Test\Libraries;

    public function hasPurchasedCorrectProducts()
    {
        $testData = [];
        $testData['one'] = new \stdClass();
        $testData['one']->qty = 2;

        (new \core\Libraries\Debug())->printData($testData, false); // see below #1

        (new StupidTest())->test($testData);

        (new \core\Libraries\Debug())->printData($testData, false);exit; // see below #3
    }
}


<?php
namespace core\Test\Libraries;

    class StupidTest
    {
        private $availableProducts;

        public function test($availableProducts)
        {
            $this->availableProducts = $availableProducts;
            $this->availableProducts['one']->qty = ($this->availableProducts['one']->qty - 1)
;
            (new \core\Libraries\Debug())->printData($this->availableProducts, false); // see below #2
        }
   }

1

Array
(
    [one] => stdClass Object
        (
            [qty] => 2
        )

)

2

Array
(
    [one] => stdClass Object
        (
            [qty] => 1
        )

)

3

Array
(
    [one] => stdClass Object
        (
            [qty] => 1
        )

)

How is $testData in #3 getting updated?

2 Answers 2

1

A stdClass (like any other class too) isn't copied when the array is passed.

The stdClass you have in your calling function is exactly the same than the one in your called function.

So as it's the same, any change on it will be also affect what you get in your calling function.

So, use an array instead of stdClass, if that behavior is not wanted.

Sign up to request clarification or add additional context in comments.

Comments

1

Classes are always passed by reference in PHP. StdClass is no exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.