PHP-间接修改重载属性

PHP-间接修改重载属性,第1张

PHP-间接修改重载属性

很好,你给了我一些玩的东西

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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5065315.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存