Php Laravel 5.0-调用basecontroller中的用法?
这是我的Controller.php,其他所有控制器都从中扩展。我希望这样做Php Laravel 5.0-调用basecontroller中的用法?,php,laravel,controller,laravel-5,Php,Laravel,Controller,Laravel 5,这是我的Controller.php,其他所有控制器都从中扩展。我希望这样做 <?php namespace App\Http\Controllers; use App\User; use App; use URL; use App\City; use Illuminate\Foundation\Bus\DispatchesCommands; use Illuminate\Routing\Controller as BaseController; use Illuminate\Fou
<?php
namespace App\Http\Controllers;
use App\User;
use App;
use URL;
use App\City;
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
abstract class Controller extends BaseController {
use DispatchesCommands, ValidatesRequests;
}
但这确实:
namespace App\Http\Controllers;
use App\User;
use App;
use URL;
use App\City;
class HomeController extends Controller { .... }
这正常吗?这一定很痛苦吗:-)每个控制器中都使用了一些类,我每次都需要调用它们,这有点奇怪
注意:我正在从4.2迁移,希望使用名称空间
谢谢 不幸的是,这是不可能的,因为您不能“继承”
使用
语句。以下注释摘自上的PHP文档:
注意:
导入规则基于每个文件,这意味着包含的文件将不会继承父文件的导入规则
因此,您需要根据需要在每个文件中声明使用语句
导入是在编译时而不是运行时完成的。这不是PHP特有的,例如Javaimport
语句和C#using
语句不是“继承”的,因为它们不是编译的,只是编译器在编译时使用它们来解析名称空间。这些语句有助于避免在代码中使用完全限定的名称空间,这通常会使代码过于冗长且可读性较差。我建议您阅读php手册中的以下页面:
考虑以下代码:
<?php
namespace App;
use App\User;
class MyClass extends Controller
{
public function __construct()
{
new User(); // we refer to the App\User
}
}
//another file
<?php
namespace App\AnotherNamespace;
class MySecondClass extends Controller
{
public function __construct()
{
new User(); // I refer to App\AnotherNamespace\User
}
}
谢谢您的详细解释!是的,我将迁移到5.1,但从4.2开始,显然您必须通过5.0:-),因此我将在每个控制器中添加正确的名称空间。我还需要多读一点,这个部分的结构目前对我来说还很模糊。@commandantp,不客气\u construct
是构造函数,在实例化对象时调用它。
<?php
namespace App;
use App\User;
class MyClass extends Controller
{
public function __construct()
{
new User(); // we refer to the App\User
}
}
//another file
<?php
namespace App\AnotherNamespace;
class MySecondClass extends Controller
{
public function __construct()
{
new User(); // I refer to App\AnotherNamespace\User
}
}