ラッパークラスを使う場合にはコンストラクタで引数を使う
かなり変則的な状況だけど、詰まったのでメモしておく。 Smartyなどのインスタンスをラッパークラスで管理して、なおかつそのラッパークラスを別のクラスで利用して、そのなかでSmartyのクラス変数を利用する。みたいな。 言葉で説明するのが面倒だな。ソースを見てください
<?php
class test1 {
public $a='test';
public function get_a() {
return $this->a;
}
}
class test2 {
public $obj;
public function __construct() {
$this->obj = new test1();
}
public function get_obj() {
return $this->obj;
}
}
$obj1 = new test1();
$obj2 = new test2();
$obj3 = $obj2->get_obj();
$obj3->a = 'hoge';
print($obj1->get_a()); //表示は"test"
上記のコードでtest1のクラス変数$aを、代入したインスタンスの$obj3から変更するにはどうするのか?というところで詰まったのです。参照渡しをいろいろ試してみたけどダメ。解決策は下記。
<?php
class test1 {
public $a='test';
public function get_a() {
return $this->a;
}
}
class test2 {
public $obj_copy;
public function __construct($obj_org) {
$this->obj_copy = $obj_org;
}
public function get_obj() {
return $this->obj_copy;
}
}
$obj1 = new test1();
$obj2 = new test2($obj1);
$obj3 = $obj2->get_obj();
$obj3->a = 'hoge';
print($obj1->get_a()); // 表示は"hoge"
コンストラクタで引数を取ればよかっただけか。アンパサンド(&)で何とか出来ると思ったから時間がかかった。