如果建構子的參數中有引用,newInstanceArgs 函式將無法呼叫類別的建構子,因此請注意傳入的內容。
<?php
類別 Foo {
函式 __construct (&$arr) {
$this->arr = &$arr;
}
函式 createInstance () {
$reflectionClass = new ReflectionClass("Bar");
return $reflectionClass->newInstanceArgs(array($this, $this->arr));
}
函式 mod($key, $val) {
$this->arr[$key] = $val;
}
}
類別 Bar {
函式 __construct (&$foo, &$arr) {
$this->foo = &$foo;
$this->arr = &$arr;
}
函式 mod($key, $val) {
$this->arr[$key] = $val;
}
}
$arr = array();
$foo = new Foo($arr);
$arr["x"] = 1;
$foo->mod("y", 2);
$bar = $foo->createInstance();
$bar->mod("z", 3);
echo "<pre>";
print_r($arr);
print_r($foo);
print_r($bar);
echo "</pre>";
?>