Laravel数组变量创建及PHP中$user_role->role_id赋值报错解决
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 thetoArray()method:
You can also use Laravel's helper functions like$collection = collect(['name' => 'Bob', 'role' => 'admin']); $array = $collection->toArray();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

