PHP:无法读取对象

问题描述 投票:0回答:1

我已经尝试读取一个对象 3 个小时但没有成功。

我想获取这个对象内部的id。

print_r($meal)
:

App\Models\Recipe Object ( [connection:protected] => mysql [table:protected] => recipes [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [preventsLazyLoading] => [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [escapeWhenCastingToString:protected] => [attributes:protected] => Array ( [id] => 29 [recipe] => Creamy Cheese Pancakes [category] => Breakfast Recipes [meal] => breakfast [image] => Creamy_Cheese_Pancakes-Creamy_Cheese_Pancakes.jpg [calories] => 82 [created_at] => [updated_at] => ) [original:protected] => Array ( [id] => 29 [recipe] => Creamy Cheese Pancakes [category] => Breakfast Recipes [meal] => breakfast [image] => Creamy_Cheese_Pancakes-Creamy_Cheese_Pancakes.jpg [calories] => 82 [created_at] => [updated_at] => ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [classCastCache:protected] => Array ( ) [attributeCastCache:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [timestamps] => 1 [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [fillable:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) )

dd($meal)
:

App\Models\Recipe {#1388 ▼
  #connection: "mysql"
  #table: "recipes"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #escapeWhenCastingToString: false
  #attributes: array:8 [▶]
  #original: array:8 [▶]
  #changes: []
  #casts: []
  #classCastCache: []
  #attributeCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▶]
}

如果我这样做

print_r($meal->id)
print_r($meal['id'])
dd($meal->id)
我会得到 id:

29

但是如果我这样做

$id = $meal['id']
,我就会明白:

Undefined array key "id"

如果我这样做

$id = $meal->id
:

Attempt to read property "id" on array

我不明白为什么。

我尝试过:

$id = $meal[0]['id'];

还尝试过:

$json_decode = json_decode($meal, true);
$id = $json_decode['id'];

我做错了什么?

php
1个回答
0
投票

您必须在类或派生类中进行

print_r
操作,并在类或派生类之外进行赋值操作:

Protected
属性和方法只能由类中使用 定义了哪些属性或方法以及派生的任何类 从中。任何其他代码都无法使用它们。

© www.soinside.com 2019 - 2024. All rights reserved.