php Laravel全局辅助函数`optional()`

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php Laravel全局辅助函数`optional()`相关的知识,希望对你有一定的参考价值。

<?php

use App\Support\HigherOrderOptionalProxy;

if (!function_exists('optional')) {
    /**
     * Allow arrow-syntax access of optional objects by using a higher-order
     * proxy object. The eliminates some need of ternary and null coalesce
     * operators in Blade templates.
     *
     * @param mixed|null $value
     *
     * @return HigherOrderOptionalProxy
     */
    function optional($value)
    {
        return new HigherOrderOptionalProxy($value);
    }
}
<?php

namespace App\Support;

class HigherOrderOptionalProxy
{
    /**
     * The target being transformed.
     * Use _ prefix to avoid namespace conflict on __get()
     *
     * @var mixed
     */
    protected $_target;

    /**
     * Create a new transform proxy instance.
     *
     * @param mixed $target
     */
    public function __construct($target)
    {
        $this->_target = $target;
    }

    /**
     * Dynamically pass property fetching to the target when it's present.
     *
     * @param string $property
     *
     * @return mixed
     */
    public function __get($property)
    {
        if (is_object($this->_target)) {
            return $this->_target->{$property};
        }
    }

    /**
     * Dynamically pass method calls to the target when it's present.
     *
     * @param string $method
     * @param array  $parameters
     *
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        if (is_object($this->_target)) {
            return $this->_target->{$method}(...$parameters);
        }
    }

    /**
     * Allow optional(null)->present()->prop to return null without a decorated
     * null dereference exception.
     *
     * @return HigherOrderOptionalProxy|mixed
     */
    public function present()
    {
        if (is_object($this->_target)) {
            return $this->_target->present(...func_get_args());
        }

        return new HigherOrderOptionalProxy(null);
    }
}

以上是关于php Laravel全局辅助函数`optional()`的主要内容,如果未能解决你的问题,请参考以下文章

PHP 全局使用 Laravel 辅助函数 dd

laravel 5.5 《电商实战 》辅助函数

php 示例SVG和Markdown辅助函数#laravel #php

Laravel Vuejs 实战:开发知乎 (33)自定义helper方法

laravel根目录的PHP文件中怎么引用门面类或辅助函数?

php--一些有用的Laravel辅助函数