Strange behavior adding this object to this static array

I am currently testing 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 so 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 did my added object change?

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

+3
source share
3 answers

This is because your object (i.e. $thisin the internal context) will be copied by reference , not by value. To make a copy by value, you need to do:

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

As an alternative, you need to instantiate (for example, constructs such as new self- but cloneseem to be more flexible here) your object as many times as you want to copy.

, , . var_dump() print_r() - , . (.. ):

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"
  }
}

- , .

+2

2 $_alerts. - :

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

        private function __construct($type,$message){
                $this->type=$type;
                $this->message = $message;
        }

        public function getMessage(){
                return $this->message;
        }

        public function getType(){
                return $this->type;
        }

        public static function add($type, $message) {
            self::$_alerts[] = new self($type,$message);
        }
    }


    Alert::add("warning", "test 1");
    Alert::add("error", "test 2");

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

, , , . , "" " 1", .

, :

$alert = new Alert();

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

$alert2 = new Alert();
$alert2->add("error", "test 2");

:

Array
(
    [0] => Alert Object
    (
        [type:Alert:private] => warning
        [message:Alert:private] => test 1
    )

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

)
+1

All Articles