codemagpie/array2object

高性能,支持将数组转换为对象,对象转换为数组,易于使用

1.0.1 2022-05-27 06:41 UTC

This package is auto-updated.

Last update: 2024-09-27 11:43:24 UTC


README

简介

支持将数组转换为对象,对象转换为数组,易于使用

安装

composer require codemagpie/array2object

用法1

只需声明类属性类型

use CodeMagpie\ArrayToObject\AbstractBaseObject

class User extends AbstractBaseObject
{
    public string $name;
    
    public int $age;
    
    public User $child;
    /** 
     * @var User[] 
     */
    public array $children;
}

使用

$arr = [
    'name' => 'test',
    'age' => '17',
    'child' => [
        'name' => 'test1',
        'age' => '17',
    ],
    'children' => [
        [
            'name' => 'test2',
            'age' => '17',
        ],
    ],
];
$user = new User($arr);
// if the user object does not extend AbstractBaseObject, you should use:
// $user = new User();
// \CodeMagpie\ArrayToObject\ArrayToObjectBuilder::create()->bind($user);
// echo \CodeMagpie\ArrayToObject\Utils\DataHelper::objectToArray($user); // Array
echo $user->name; // test
echo $user->age; // 17
echo $user->child->name; // test1
echo $user->children[0]->name; // test2
echo $user->toArray() //Array. if extend ArrayToObjectBuilder

用法2

只需在类的注释中声明属性类型

use CodeMagpie\ArrayToObject\AbstractLightBaseObject

/**
 * @property string $name
 * @property int $age
 * @property User $child
 * @property User[] $children
 */
class User extends AbstractLightBaseObject
{
}

使用

$arr = [
    'name' => 'test',
    'age' => '17',
    'child' => [
        'name' => 'test1',
        'age' => '17',
    ],
    'children' => [
        [
            'name' => 'test2',
            'age' => '17',
        ],
    ],
];
$user = new User($arr);
// if the user object does not extend AbstractLightBaseObject, you should use:
// $user = new User();
// \CodeMagpie\ArrayToObject\ArrayToObjectBuilder::createFormPropertyDocParser()->bind($user);
// echo \CodeMagpie\ArrayToObject\Utils\DataHelper::objectToArray($user);// Array
echo $user->name; // test
echo $user->age; // 17
echo $user->child->name; // test1
echo $user->children[0]->name; // test2
echo $user->toArray() //Array. if extend AbstractLightBaseObject

用法性能比较