设未定义 属性 为 Laravel 中的空值

Let undefined property be null value in Laravel

有没有办法让未定义的对象属性变成空值?

因为 laravel 请求对象会自动使未定义的 属性 变成空值,如下所示。

$request->test; // This parameter never passed
error_log($request->test) //null

但是当涉及到对象或数组时,它会抛出错误。

$object->test // test is not defined
//Will throw ErrorException: Undefined property

它们有什么区别?

使用isset($your_object->its_propery)。 isset() 将 return false 如果未定义,否则它 return true.

区别在于Request class 有魔法方法__get (check this) 如果参数return null您要求的请求参数中不存在。

因此,例如 $request->test; 不会被解释为 "go and grab the test attribute of that object",而是 运行 Class 的 __get($value) 方法,它将检查请求参数中是否存在 $value(在本例中为 test),如果存在,该方法将 return 该值,如果不存在,将 return null ,相反,如果你不 create/have 你的 class 中的魔术方法 __get,PHP 将只检查 test 是否是你的属性class,否则会return undefined.

您始终可以使用 isset($value) 函数

检查是否 undefined

laravel 请求对象使用魔术方法 __get 实际从请求中获取输入元素。这是它在幕后的工作方式。

    /**
 * Get an input element from the request.
 *
 * @param  string  $key
 * @return mixed
 */
public function __get($key)
{
    return Arr::get($this->all(), $key, function () use ($key) {
        return $this->route($key);
    });
}

您可以使用__get魔术方法来避免未定义的属性访问异常,如下所示

    /**
 * check if attribute exists or not, if not exists return null.
 *
 * @param  string  $key
 * @return mixed|null
 */
public function __get($key)
{
    return isset($this->{$key})?$this->{$key}:null;
}