受保护的方法可用于继承类,路由器尝试在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 函数,因为它是父类私有的
希望对你有帮助