请教 request () 中的 input () 方法 和 get () 方法 有什么区别,请大神指点一下

请教大神们详细说一下这两个 方法有什么区别,在此感谢了

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 3

两个都可以获取用户输入的数据,不同的是, get() 方法是 Symfony\Component\HttpFoundation\Request 提供的一个方法,他的源码是这样的。

public function get($key, $default = null)
{
    if ($this !== $result = $this->attributes->get($key, $this)) {
        return $result;
    }

    if ($this !== $result = $this->query->get($key, $this)) {
        return $result;
    }

    if ($this !== $result = $this->request->get($key, $this)) {
        return $result;
    }

    return $default;
}

在Laravel中是不推荐使用的,Laravel中推荐使用的是Laravel自己的方法 input()

5年前 评论

input() 方法是 Laravel框架自带的方法, 在 Illuminate\Http\Request里, Request 继承的是Symfony\Component\HttpFoundation\Request

/**
     * Retrieve an input item from the request.
     *
     * @param  string  $key
     * @param  string|array|null  $default
     * @return string|array
     */
    public function input($key = null, $default = null)
    {
        $input = $this->getInputSource()->all() + $this->query->all();

        return Arr::get($input, $key, $default);
    }

get() 方法则在 Symfony框架中, 在 Symfony\Component\HttpFoundation\Request

/**
     * Gets a "parameter" value.
     *
     * This method is mainly useful for libraries that want to provide some flexibility.
     *
     * Order of precedence: GET, PATH, POST
     *
     * Avoid using this method in controllers:
     *
     *  * slow
     *  * prefer to get from a "named" source
     *
     * It is better to explicitly get request parameters from the appropriate
     * public property instead (query, attributes, request).
     *
     * @param string $key     the key
     * @param mixed  $default the default value if the parameter key does not exist
     * @param bool   $deep    is parameter deep in multidimensional array
     *
     * @return mixed
     */
    public function get($key, $default = null, $deep = false)
    {
        if ($this !== $result = $this->query->get($key, $this, $deep)) {
            return $result;
        }

        if ($this !== $result = $this->attributes->get($key, $this, $deep)) {
            return $result;
        }

        if ($this !== $result = $this->request->get($key, $this, $deep)) {
            return $result;
        }

        return $default;
    }

两者都是获取请求参数的值

5年前 评论
ruke

有些情况下get会取不到值, 用input可以取到, 我上次除了一次bug, 就是因为get没取到值

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!