You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel数组变量创建及PHP中$user_role->role_id赋值报错解决

Answers to Your Laravel/PHP Questions

Hey there! Let's tackle your two tech questions one by one:

1. How to Create Array Variables in Laravel

Creating arrays in Laravel works just like standard PHP (since Laravel is built on PHP). Here are the most common ways to do it:

  • Basic indexed array:
    $fruits = ['apple', 'banana', 'orange'];
    // Or the older syntax if you prefer:
    $fruits = array('apple', 'banana', 'orange');
    
  • Associative array (key-value pairs):
    $userInfo = [
        'name' => 'Alice',
        'age' => 30,
        'email' => 'alice@example.com'
    ];
    
  • Laravel-specific array workflows:
    If you're working with Laravel Collections, you can convert them to arrays with the toArray() method:
    $collection = collect(['name' => 'Bob', 'role' => 'admin']);
    $array = $collection->toArray();
    
    You can also use Laravel's helper functions like array_add() to modify arrays easily:
    $userInfo = array_add($userInfo, 'phone', '123-456-7890');
    

2. Fixing the "Attempt to assign property of non-object" Error

That error pops up because you tried to use object syntax (->) on an array. Let's break down what went wrong and how to fix it:

Why the error happens

Your code initializes $user_role as an array with $user_role = array();, but then tries to assign a property to it like an object with $user_role->role_id='1';. Arrays use square brackets [] for access, while objects use ->—mixing these two causes the error.

Correct solutions

Pick the approach that fits your needs:

Option 1: Use a stdClass object (simple, for basic object needs)

// Create an empty object
$user_role = new stdClass();
// Assign the property
$user_role->role_id = '1';
// Print the value
print_r($user_role->role_id); // Outputs: 1

Option 2: Cast an array to an object

If you want to start with an array but use object syntax later, cast it to an object with (object):

$user_role = (object) ['role_id' => '1'];
print_r($user_role->role_id); // Outputs: 1

Option 3: Stick with an associative array (if object syntax isn't necessary)

Adjust your code to use array syntax instead:

$user_role = array();
$user_role['role_id'] = '1';
print_r($user_role['role_id']); // Outputs: 1

内容的提问来源于stack exchange,提问作者user3386779

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:48:37