stdClass
是 PHP 的一个内置类,用于创建通用对象。它是 PHP 的"空"类,没有预定义的属性和方法,但可以动态添加属性。
$obj = new stdClass();
$obj->property = 'value';
PHP 数组是键值对的集合,可以是索引数组或关联数组。
$array = ['key' => 'value'];
json_decode()
默认返回 stdClass 对象array_map()
, array_filter()
等$user = new stdClass();
$user->name = 'John';
$user->age = 30;
$user->email = 'john@example.com';
function greet(stdClass $user) {
return "Hello, {$user->name}!";
}
$user = [
'name' => 'John',
'age' => 30,
'email' => 'john@example.com'
];
function processUser(array $user) {
return array_map('strtoupper', $user);
}
json_decode($json, true)
获取数组// 数组转对象
$obj = (object)$array;
// 对象转数组
$array = (array)$obj;
选择使用 stdClass
还是数组主要取决于你的具体需求、代码上下文和个人/团队偏好。
没有搜到相关的文章