[英]How to Stop Chaining Methods at Null Value - PHP
當鏈中的某個鏈接返回null時,是否可以停止鏈接方法? 例如,我有一個這樣的數組集合:
class ArrayCollection {
protected $array;
public function __construct(Array $array = array()) {
$this->array = $array;
}
public function get($key) {
try {
$result = $this->array[$key];
return $result;
}
catch (\Exception $e) {
return;
}
}
}
然后我有一個數組,它被轉換成這樣的數組集合:
$fm = array(
'template' => 'default',
'title' => 'Home'
);
然后,我嘗試訪問模板中不存在的數組鍵,如下所示:
<?php echo $page->get('fm')->get('test')->get('test'); ?>
我希望最后一段模板代碼返回null,而不是拋出錯誤。 $page->get('fm')
返回一個數組集合,但是如果數組集合上的get方法返回null,則Call to a member function get() on null
的Call to a member function get() on null
。 如果我返回一個空數組集合,則在鏈的末尾,我Object of class ArrayCollection could not be converted to string
。
當然,我可以將我的模板代碼包裝在try ... catch
塊中,但這並不完全理想。 也許我會以錯誤的方式進行操作? 有沒有人有辦法解決嗎?
您基本上是在嘗試對Null值調用函數。 我認為這是不可能的。 解決此問題的最佳方法是嘗試/捕獲塊。 但是,正如您明確提到的那樣,您不想使用一個,您可以添加驗證。
<?php
if ((!is_null($page)) && (!is_null($page->get('fm'))))
if(!is_null($page->get('fm')->get('test')))
echo $page->get('fm')->get('test')->get('test');
else
return null;
else
return null;
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.