简体   繁体   English

如何安全地检索此对象的此属性?

[英]How can I safely retrieve this property of this object?

I have a Stripe subscription object that looks like this... 我有一个Stripe订阅对象,看起来像这样......

subscription: {
    items: {
        data: [
            plan: {
                id: 'my_plan_id'
            }
        ]
    }
}

What's the best way to safely retrieve the plan id? 安全检索计划ID的最佳方法是什么? Currently I am doing the following. 目前我正在做以下事情。

'plan_id' => $subscription->items->data[0]->plan->id,

But, it looks like that will fail if items , data[0] , or plan , is not set. 但是,如果未设置itemsdata[0]plan ,则看起来会失败。 I could do nest if statements like, if (isset($subscription->items) && isset(data[0]) ... , but I am not sure that is the best way. 我可以做if if if (isset($subscription->items) && isset(data[0]) ...类的语句,但我不确定这是最好的方法。

Is there a PHP method or Laravel method that I can use to extract that property safely that would be cleaner than that? 是否有一个PHP方法或Laravel方法可以用来安全地提取那个比那更干净的属性?

If you're using PHP 7+, you can use the null coalesce operator: 如果您使用的是PHP 7+,则可以使用null coalesce运算符:

'plan_id' => $subscription->items->data[0]->plan->id ?? $default,

This will evaluate the value if it's available, otherwise it will use the default, without generating any warnings or errors. 这将评估值是否可用,否则将使用默认值,而不会生成任何警告或错误。

Example: 例:

$foo = new stdClass();
var_dump($foo->bar->baz->data[0]->plan->id ?? null);

Output: 输出:

NULL

您可以在整个选择器上使用isset函数:

isset($subscription->items->data[0]->plan->id) ? $subscription->items->data[0]->plan->id : null;

A rather cumbersome but generic method to access nested structures by a list of keys; 通过键列表访问嵌套结构的一种相当麻烦但通用的方法; can be made into a reusable function easily: 可以很容易地成为可重用的功能:

$id = array_reduce(['items', 'data', 0, 'plan', 'id'], function ($o, $k) {
    if (!$o) {
        return null;
    } else if (is_array($o) && isset($o[$k])) {
        return $o[$k];
    } else if (isset($o->$k)) {
        return $o->$k;
    }
}, $subscription);

you can take help of ternary condition to check if the value is set or not. 你可以利用ternary condition来检查是否设置了值。 If set then put that value otherwise put default as 如果设置然后放置该值,否则将默认值设置为

$id=isset($subscription->items->data[0]->plan->id) ? $subscription->items->data[0]->plan->id : $your_dafault_value;

If the value is set then the $id looks like 如果设置了值,则$id看起来像

$id='my_plan_id';//In most cases we should consider null as a default value

If the value is not set then the $id looks liks 如果未设置该值,则$id看起来像是liks

 $id='your_dafault_value';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM