如何避免在命名空间类中使用反斜杠和“use”来调用全局类?

问题描述 投票:4回答:1

我有很多命名空间类,我在其中对全局类进行了大量调用。

我有2个解决方案:

1-我在每个全局类调用中使用反斜杠“\”

namespace Admin;

class UserController extends \BaseController{
  [...]
  public function update($id){
    $user = new \User::find($id);
    $user->username = \Input::get('username');
    $user->password = \Hash::make(\Input::get('password'));
    return \Redirect::action('UserController@index');
  }
  [...]
}

2-我在每个命名空间类的开头用“use”声明了很多全局类的用法

namespace Admin;
use \BaseController;
use \User;
use \Input;
use \Hash;
use \Redirect;

class UserController extends BaseController{
  [...]
  public function update($id){
    $user = new User::find($id);
    $user->username = Input::get('username');
    $user->password = Hash::make(Input::get('password'));
    return Redirect::action('UserController@index');
  }
  [...]
}

在这两种情况下,我认为代码不是那么优雅。有办法避免这种情况吗?我想保留命名空间并调用全局类,而不在每个命名空间类中“使用”它们。

php namespaces
1个回答
6
投票

当你use你不必放斜线,你可以只:

use BaseController;
use User;
use Input;
use Hash;
use Redirect;

这意味着PHP将尝试从root(\)开始。

但如果您的类是命名空间,则无法避免使用use。这是告诉PHP这些文件不在你的同一名称空间中的方法。

© www.soinside.com 2019 - 2024. All rights reserved.