PHP类动态属性问题
动态属性问题给程序带来很多麻烦,以下是一位朋友的解决方法如下:
From : http://bbs.php100.com/read-htm-tid-25526.html
<?php class testClass { private $va; private $vb; private $vc; private $allVars; public function __construct(){ echo 'testClass __construct'.'</br>'; //$this->va = 1; $this->getAllVars(); } public function __GET($name) { return $this->$name; } public function __SET($name, $value) { foreach($this->allVars as $key) { if ($name == "$key") { $this->$name = $value; return; } } throw new exception ('你访问了未定义的属性'); } private function getAllProps() { $r = new ReflectionClass($this); return ($r->getProperties()); } private function getAllVars() { $classProps = $this->getAllProps(); foreach($classProps as $key) { $temparr = get_object_vars($key); $this->allVars[] .= $temparr['name']; } } } $rc = new testClass(); $rc->va = 5; $rc->vb = 5; $rc->vc = 5; $rc->vd = 6; ?>
申明
非源创博文中的内容均收集自网上,若有侵权之处,请及时联络,我会在第一时间内删除.再次说声抱歉!!!
博文欢迎转载,但请给出原文连接。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步