如何检查 属性 是否已定义并在 PHP 中提供替代项?
How to check if property is defined and provide a substitute in PHP?
我的服务有时 returns
$business->price
设置有时不和我的代码
$feature['properties']['price'] = $business->price;
抛出错误
Undefined property: stdClass::$price'
在那种情况下。
检查 属性 是否设置的最短方法是什么,如果是,则 return 是值,但如果不是,则 return 一些预定义值,如 0
或 NULL
?
三元运算符,不设置价格为0
$feature['properties']['price'] = $business->price ? $business->price : 0;
在php中使用三元运算符总是安全的。这是一个例子,
$retVal = (condition) ? a : b ;
如@hassan 所述,在你的情况下,
$feature['properties']['price'] = (isset($business->price) ? $business->price : 'some_default');
但是,这里最大的错误是您的代码如何处理 类。在尝试使用 isset 函数之前,首先应该尽量避免在第一时间出现错误。我认为您的代码可能构造不当。
我的服务有时 returns
$business->price
设置有时不和我的代码
$feature['properties']['price'] = $business->price;
抛出错误
Undefined property: stdClass::$price'
在那种情况下。
检查 属性 是否设置的最短方法是什么,如果是,则 return 是值,但如果不是,则 return 一些预定义值,如 0
或 NULL
?
三元运算符,不设置价格为0
$feature['properties']['price'] = $business->price ? $business->price : 0;
在php中使用三元运算符总是安全的。这是一个例子,
$retVal = (condition) ? a : b ;
如@hassan 所述,在你的情况下,
$feature['properties']['price'] = (isset($business->price) ? $business->price : 'some_default');
但是,这里最大的错误是您的代码如何处理 类。在尝试使用 isset 函数之前,首先应该尽量避免在第一时间出现错误。我认为您的代码可能构造不当。