很好,你给了我一些玩的东西
跑
class Sample extends Creator {}$a = new Sample ();$a->role->rolename = 'test';echo $a->role->rolename , PHP_EOL;$a->role->rolename->am->love->php = 'w00';echo $a->role->rolename , PHP_EOL;echo $a->role->rolename->am->love->php , PHP_EOL;
输出量
testtestw00
使用的班级
编辑:根据要求提供新阵列支持abstract class Creator { public function __get($name) { if (! isset ( $this->{$name} )) { $this->{$name} = new Value ( $name, null ); } return $this->{$name}; } public function __set($name, $value) { $this->{$name} = new Value ( $name, $value ); }}class Value extends Creator { private $name; private $value; function __construct($name, $value) { $this->name = $name; $this->value = $value; } function __toString() { return (string) $this->value ; }}
class Sample extends Creator {}$a = new Sample ();$a->role = array ( "A", "B", "C" );$a->role[0]->nice = "OK" ;print ($a->role[0]->nice . PHP_EOL);$a->role[1]->nice->ok = array("foo","bar","die");print ($a->role[1]->nice->ok[2] . PHP_EOL);$a->role[2]->nice->raw = new stdClass();$a->role[2]->nice->raw->name = "baba" ;print ($a->role[2]->nice->raw->name. PHP_EOL);
输出量
Ok die baba
改良班
abstract class Creator { public function __get($name) { if (! isset ( $this->{$name} )) { $this->{$name} = new Value ( $name, null ); } return $this->{$name}; } public function __set($name, $value) { if (is_array ( $value )) { array_walk ( $value, function (&$item, $key) { $item = new Value ( $key, $item ); } ); } $this->{$name} = $value; }}class Value { private $name ; function __construct($name, $value) { $this->{$name} = $value; $this->name = $value ; } public function __get($name) { if (! isset ( $this->{$name} )) { $this->{$name} = new Value ( $name, null ); } if ($name == $this->name) { return $this->value; } return $this->{$name}; } public function __set($name, $value) { if (is_array ( $value )) { array_walk ( $value, function (&$item, $key) { $item = new Value ( $key, $item ); } ); } $this->{$name} = $value; } public function __toString() { return (string) $this->name ; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)