【PHP学习笔记】基于反射的数组转实体对象方案

最近有个需求,要把数据库里查出来的数据转成对应的实体对象(自定义的实体对象)

php数组转对象网上提供了一个这样的方法

function array_to_object($arr)
{
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }

    return (object)$arr;
}

$arr = ['name' => "aa", "id" => 3, "age" => ['name' => "aa", "id" => 3, "age" => 2]];
var_dump(array_to_object($arr));

能转没毛病,,但是php的数组转对象貌似可以更简单更通俗(json序列化,再json反序列化成对象)

var_dump(json_decode(json_encode($arr)));

这仅仅是数组转对象的方案,,想转实体对象(自己定义的对象)还需要用反射,下面提供简单实例:

/**
 * 测试类Student
 * Class Student
 */
class Student
{
    private $name;
    private $id;

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name): void
    {
        $this->name = $name;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id): void
    {
        $this->id = $id;
    }

}

/**
 * 【1】反射创建类的操作对象,$reflectionClass
 * 【2】创建临时代理对象$obj
 * 【3】将参数逐一赋值给$obj
 * 【4】那么此时的$obj就是数组对应的实体类(此处不包含嵌套,只支持简单对象转)
 * @param array  $arr
 * @param string $className
 *
 * @return object
 * @throws ReflectionException
 */
function arrayToSimpleObj(array $arr, string $className)
{
    $reflectionClass = new ReflectionClass($className);
    $obj             = $reflectionClass->newInstance();
    foreach ($arr as $key => $value) {
        $property = $reflectionClass->getProperty($key);
        $property->setAccessible(true);//私有属性需要设置允许访问
        $property->setValue($obj, $value);
    }
    
    return $obj;
}

$arr = ['name' => "aa", "id" => 3];
try {
    var_dump(arrayToSimpleObj($arr, Student::class));
} catch (ReflectionException $e) {
    echo "转换失败";
}

$arr = ['name' => "aa", "id" => 3, "age" => 2];
try {
    var_dump(arrayToSimpleObj($arr, Student::class));
} catch (ReflectionException $e) {
    echo "转换失败";
}

你可能感兴趣的:(PHP学习笔记)