合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
# thinkphp5方法注入 如果你需要在`Request`请求对象中添加自己的方法,可以使用`Request`对象的方法注入功能,例如: ``` <pre class="calibre14">``` <span class="token3">publicfunction index</span><span class="token1">(</span><span class="token1">)</span> <span class="token1">{</span> Request<span class="token1">:</span><span class="token1">:</span><span class="token3">hook</span><span class="token1">(</span><span class="token4">'user'</span><span class="token1">,</span><span class="token4">'userinfo'</span><span class="token1">)</span><span class="token1">;</span> <span class="token6">//绑定user方法指向userinfo方法</span> $data <span class="token">=</span> Request<span class="token1">:</span><span class="token1">:</span><span class="token3">instance</span><span class="token1">(</span><span class="token1">)</span><span class="token">-</span><span class="token">></span><span class="token3">user</span><span class="token1">(</span><span class="token5">1</span><span class="token1">)</span><span class="token1">;</span> <span class="token2">return</span> $data<span class="token1">;</span> <span class="token1">}</span> userInfo函数须写在common<span class="token1">.</span>php中 : <span class="token">/</span>\<span class="token">*</span>\<span class="token">*</span>使用hook方法注入 \<span class="token">*</span><span class="token">/</span> use think\\Request<span class="token1">;</span> <span class="token6">//方法注入的函数</span> <span class="token2">function</span><span class="token3"> userInfo</span><span class="token1">(</span>Request $request<span class="token1">,</span> $userId<span class="token1">)</span> <span class="token1">{</span> <span class="token2">return</span><span class="token4">"I am id is "</span><span class="token1">.</span>$userId<span class="token1">;</span> <span class="token1">}</span> 必须引入Request 方法 浏览器访问index方法的时候 输出<span class="token5">I</span> am id is <span class="token5">1</span> ``` ```