最近学习zend框架,
// 给出一个配置数据的数组$configArray = array( 'webhost' => 'www.example.com', 'database' => array( 'adapter' => 'pdo_mysql', 'params' => array( 'host' => 'db.example.com', 'username' => 'dbuser', 'password' => 'secret', 'dbname' => 'mydatabase' ) ));// 基于配置数据创建面向对象的 wrapper $config = new Zend_Config($configArray);// 输出配置数据 (结果在'www.example.com'中)echo $config->webhost;// 使用配置数据来连接数据库$db = Zend_Db::factory($config->database->adapter, $config->database->params->toArray());// 另外的用法:简单地传递 Zend_Config 对象。// Zend_Db factory 知道如何翻译它。$db = Zend_Db::factory($config->database);
发现了很多诸如
$config->database->adapter
此类访问的现象。$config是对象,但是database和adapter不是对象,但是怎么用到了"->"符号呢?
怀着探索的精神,阅读了一下congfig.php和ini.php,很多函数就不是很明白,看了一天晕乎乎的。晚上自己把原始类复制过来,自己加数据测试,终于发现了原因。
class test{ protected $data; public function __construct(array $array){
foreach ($array as $key => $value) { if (is_array($value)) { $this->data[$key] = new self($value); } else { $this->data[$key] = $value; } }
} public function get($name, $default = null) { $result = $default; if (array_key_exists($name, $this->data)) { $result = $this->data[$name]; } return $result; } public function __get($name) { return $this->get($name); }}$array["general"]=array("name"=>"tom","sex"=>"male");
$test=new test($array);print_r($test);
echo $test->general->name;
打印出的$test 是
test Object( [data:protected] => Array ( [general] => test Object ( [data:protected] => Array ( [name] => tom [sex] => male )
)
)
)
里面其实主要原理是用到了魔术方法__get(),当 $test->general->name去访问时发现没有general这个成员,它就自动调用魔术方法,这样$test->general就返回了一个 test Object,然后继续->name就自然明白了。