为了账号安全,请及时绑定邮箱和手机立即绑定

对于Laravel控制器修饰符的疑问

对于Laravel控制器修饰符的疑问

PHP
小唯快跑啊 2019-03-08 17:14:19
为什么Laravel控制器使用protected修饰也可以正常访问? protected function advert() { try { $result = $this->systemService->advert (); return $this->response->array (Response::return (200, '获取成功', $result)); } catch (\Exception $e) { return $this->response->array (Response::return (0, $e->getMessage ())); } } 就算使用反射实例化也不能访问protected修饰的方法吧,laravel源码如下 $constructor = $reflector->getConstructor(); // If there are no constructors, that means there are no dependencies then // we can just resolve the instances of the objects right away, without // resolving any other types or dependencies out of these containers. if (is_null($constructor)) { array_pop($this->buildStack); return new $concrete; } $dependencies = $constructor->getParameters(); // Once we have all the constructor's parameters we can create each of the // dependency instances and then use the reflection instances to make a // new instance of this class, injecting the created dependencies in. $instances = $this->resolveDependencies( $dependencies ); array_pop($this->buildStack); return $reflector->newInstanceArgs($instances);
查看完整描述

1 回答

?
开心每一天1111

TA贡献1836条经验 获得超13个赞

Illuminate\Routing\Controller 这是laravel调用控制器方法的方法

public function dispatch(Route $route, $controller, $method)
{
    
    $parameters = $this->resolveClassMethodDependencies(
        $route->parametersWithoutNulls(), $controller, $method
    );

    if (method_exists($controller, 'callAction')) {

            return $controller->callAction($method, $parameters);
    }
        
    return $controller->{$method}(...array_values($parameters));
}

Laravel通过controller继承的callAction去调用子类的指定方法,也就是我们希望调用的自定义方法。

public function callAction($method, $parameters)
{
    return call_user_func_array([$this, $method], $parameters);
}

因为是继承自父类,所以父类能调用子类的保护的方法也是自然的了。

查看完整回答
反对 回复 2019-03-18
  • 1 回答
  • 0 关注
  • 338 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信