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
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:As an alternative, you'll need to instantiate (that is, for example, constructions like
new self
- butclone
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 ofprint_r()
- then you'll see that objects are actually same. Sample for your code (i.e. where copying is not fixed yet):-as you can see, objects are same there.