简体   繁体   English

如何以零值停止链接方法-PHP

[英]How to Stop Chaining Methods at Null Value - PHP

Is it possible to stop chaining methods when a certain link in the chain returns null? 当链中的某个链接返回null时,是否可以停止链接方法? For example, I have an array collection like this: 例如,我有一个这样的数组集合:

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;
        }
    }

}

And then I have an array that gets converted into an Array Collection like this: 然后我有一个数组,它被转换成这样的数组集合:

$fm = array(
    'template' => 'default',
    'title' => 'Home'
); 

I then try to access a non-existing array key in a template like this: 然后,我尝试访问模板中不存在的数组键,如下所示:

<?php echo $page->get('fm')->get('test')->get('test'); ?>

I'd like for this last piece of template code to return null, not throw an error. 我希望最后一段模板代码返回null,而不是抛出错误。 $page->get('fm') returns an array collection, but then if the get method on the array collection returns null, I get a Call to a member function get() on null . $page->get('fm')返回一个数组集合,但是如果数组集合上的get方法返回null,则Call to a member function get() on nullCall to a member function get() on null If I return an empty array collection, then at the end of the chain I get Object of class ArrayCollection could not be converted to string . 如果我返回一个空数组集合,则在链的末尾,我Object of class ArrayCollection could not be converted to string

Of course I could wrap my template code in a try ... catch block, but that's not exactly ideal. 当然,我可以将我的模板代码包装在try ... catch块中,但这并不完全理想。 Maybe I'm going about this the wrong way? 也许我会以错误的方式进行操作? Does anyone have a solution? 有没有人有办法解决吗?

You are basically trying to call a function on a Null value. 您基本上是在尝试对Null值调用函数。 This is not possible in my opinion. 我认为这是不可能的。 Best way to tackle this would be a try/ catch block. 解决此问题的最佳方法是尝试/捕获块。 However, as you have explicitly mentioned that you do not want to use one, you could add validations. 但是,正如您明确提到的那样,您不想使用一个,您可以添加验证。

<?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.

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