【问题标题】:Laravel - Get Property of objectLaravel - 获取对象的属性
【发布时间】:2023-02-25 09:58:38
【问题描述】:

我有一个名为 $shop 的对象,属于 App\Models\Shop 类,它扩展了 Illuminate\Database\Eloquent\Model

它有一个名为attributes 的属性

我需要将该属性加载到一个变量中。该模型没有该属性的吸气剂。

Illuminate\Database\Eloquent\Model 类也没有吸气剂。它只有一个__get() 方法。

我试图像这样加载属性:

$x = $shop->__get("attributes");

但它返回“空”。

【问题讨论】:

  • 为什么不在模型中添加一个吸气剂恰当的访问该属性的方法?
  • $shop->getAttributes()
  • $shop->attributes; 如果该属性可以访问。
  • @NicoHaase 这是第三方代码。
  • @TimuranBicer 不是; dd($shop) 显示 #attributes,这是一个私有成员(我想;我也看到了 +exists: true;自从我看到 +# 的意思以来已经有一段时间了)。由于 Laravel 的模型魔法,$shop->attributes 返回 null,除非 shops 有一个 attributes 列(这会很糟糕)。所以是的,->getAttributes() 是正确的,因为模型定义了那个吸气剂。

标签: php laravel


【解决方案1】:

模型为您提供访问权限的方式是:

 // Using attribute name directly
 $x = $shop->attribute;

 // Getter method
 $x = $shop->getAttribute("attribute");

在使用第一个选项的情况下,我建议使用 @property 更新类的 phpdoc 以帮助 IDE

/**
 * @property string $name
 * @property int $age
 */
class NameClass {
   protected $fillable = [
     'name',
     'age'
   ];
}

【讨论】:

    猜你喜欢
    • 2016-02-12
    • 2015-09-22
    • 2017-03-20
    • 2014-03-25
    • 2015-01-25
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多