/**
* 将数组转化成指定类型的对象<br/>
* 以对象定义的属性为主导<br/>
*
* @param array $row 参数(数组)
* @param string $className 类名称
* @return Object
*/
public static function convertArray2Class($row, $className) {
$reflect = new ReflectionClass($className);
$object = $reflect->newInstance();
$vars = get_class_vars($className);
$keys = array_keys($vars);
foreach ($keys as $key) {
if (isset($row[$key])) {
$object->$key = $row[$key];
}
}
return $object;
}
index.php
<?php
require_once 'Main/CommentsManage.php';
class Test{
var $id;
var $name;
}
$array = array('id' => 0, 'name' => 'Seraph_fd');
print_r(CommentsManage::convertArray2Class($array, "Test"));
输出:
Test Object ( [id] => 0 [name] => Seraph_fd )