【问题标题】:Why Protected methods in a controller can be invoked as a route handler为什么控制器中的受保护方法可以作为路由处理程序调用
【发布时间】:2020-02-23 04:30:00
【问题描述】:

protected 函数如何对 laravel 框架中的路由器可见?

// I have a route like this
Route::get('/bar', 'FooController@bar');

// Methods like this both work fine
public function bar() {...}
protected function bar() {...}

// But this fails 
private function bar() {...}

实例化一个控制器,然后通过后门调用protected方法似乎是不对的。 !!!!

【问题讨论】:

    标签: laravel oop controller routes protected


    【解决方案1】:

    受保护的方法可用于继承类,路由器尝试在vendor/laravel/framework/src/Illuminate/Routing/Route.php Line 219 中运行控制器操作

    protected function runController()
    {
        return $this->controllerDispatcher()->dispatch(
            $this,
            $this->getController(),
            $this->getControllerMethod()
        );
    }
    

    并使用getController 方法获取实例

    public function getController()
    {
        if (!$this->controller) {
            $class = $this->parseControllerCallback()[0];
    
            $this->controller = $this->container->make(ltrim($class, '\\'));
        }
    
        return $this->controller;
    }
    

    并将其设置为该类的 PUBLIC 属性

    /**
     * The controller instance.
     *
     * @var mixed
     */
    public $controller;
    

    因此,路由器可以通过继承逻辑使用任何公共或受保护的方法

    FooController 扩展 App\Http\Controllers\Controller 扩展了抽象类 Illuminate\Routing\Controller,它在此处调用操作

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

    子类可以调用父类的受保护方法,但不能调用私有方法

    这是一个简单的基本示例

    <?php
    
    class parenting
    {
      private function hello()
      {
        echo "private";
      }
      protected function secret()
      {
        echo "protected";
      }
    }
    
    class child extends parenting
    {
      public function foo()
      {
        // $this->hello(); // <--- Uncomment to get undefined method error 
        $this->secret();
      }
    }
    
    $child = new child();
    $child->foo();
    

    你不能调用 hello 函数,因为它是父类私有的

    希望对你有帮助

    【讨论】:

    • 对不起什么!! 父类可以调用子类的受保护方法,但不能调用私有方法 ??
    • @NavneetRamanBhaskar “声明为私有的成员只能由定义该成员的类访问。” PHP Manual - Classes and Objects - Visibility
    • @NavneetRamanBhaskar 我添加了一个简单的例子来清楚地了解这个概念
    • Parent class can call protected methods on child class 这行让我很困惑
    • 子类可以访问父类的受保护方法这是你的意思吗?
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2011-12-05
    • 2014-10-09
    • 2020-02-03
    • 1970-01-01
    • 2019-02-13
    • 2018-11-09
    相关资源
    最近更新 更多