オブジェクトの未定義のプロパティをnull値にする方法はありますか?
laravelリクエストオブジェクトは、以下のように未定義のプロパティを自動的にnull値にするためです。
$request->test; // This parameter never passed
error_log($request->test) //null
しかし、オブジェクトや配列に関しては、エラーが発生します。
$object->test // test is not defined
//Will throw ErrorException: Undefined property
それらの違いは何ですか?
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;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加