Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior adding this object to this static array

At the moment I test with this piece of code:

<?php
    class Alert {
        private $type;
        private $message;
        public static $_alerts = array();

        public function add($type, $message) {
            $this->type = $type;
            $this->message = $message;
            self::$_alerts[] = $this;
        }
    }

    $alert = new Alert();

    $alert->add("warning", "test 1");
    $alert->add("error", "test 2");

    echo "<pre>";
    print_r(Alert::$_alerts);
    echo "</pre>";

But my results are not like expected:

Array
(
    [0] => Alert Object
        (
            [type:Alert:private] => error
            [message:Alert:private] => test 2
        )

    [1] => Alert Object
        (
            [type:Alert:private] => error
            [message:Alert:private] => test 2
        )

)

Why is my added object changed?

Test area: http://codepad.viper-7.com/6q2H2A

like image 730
Ron van der Heijden Avatar asked Jul 15 '26 14:07

Ron van der Heijden


1 Answers

That's because your object (i.e. $this in internal context) will be copied by reference, not by value. To do copy by value, you'll need to do:

    public function add($type, $message) 
    {
        $this->type = $type;
        $this->message = $message;
        self::$_alerts[] = clone $this;
    }

As an alternative, you'll need to instantiate (that is, for example, constructions like new self - but clone seems to be more flexible here) your object as many times as you'll wish to copy.

By the way, there's easy way to realize what's going on. Use var_dump() instead of print_r() - then you'll see that objects are actually same. Sample for your code (i.e. where copying is not fixed yet):

array(2) {
  [0]=>
  object(Alert)#1 (2) {
    ["type":"Alert":private]=>
    string(5) "error"
    ["message":"Alert":private]=>
    string(6) "test 2"
  }
  [1]=>
  object(Alert)#1 (2) {
    ["type":"Alert":private]=>
    string(5) "error"
    ["message":"Alert":private]=>
    string(6) "test 2"
  }
}

-as you can see, objects are same there.

like image 82
Alma Do Avatar answered Jul 21 '26 11:07

Alma Do



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!