栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

PHP-间接修改重载属性

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421729.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号