有时我写
use Said\Class;
在我的php文件的顶部,如果我使用该类作为构造函数的参数,或者即使我正在实例化。
但是什么时候写整个班级名称更合适?像:
$service = new \Said\Class();
而不是宣布它?
如果我使用常量,我通常会把它写出来。但也许你应该总是将它声明在文件的顶部。不确定效率或标准方面。
答案 0 :(得分:0)
与您的示例不同,大多数命名空间都很长,因此使用use
会大大减少代码的行长度,从而使其更具可读性。
这是一个例子,你更喜欢哪个?
<?php
namespace App\Exceptions;
class Handler extends \Illuminate\Foundation\Exceptions\Handler {
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
\Illuminate\Auth\Access\AuthorizationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Foundation\Validation\ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(\Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, \Exception $e)
{
if($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException)
{
abort(404);
}
return parent::render($request, $e);
}
}
使用使用,更清洁。
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Validation\ValidationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler {
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if($e instanceof ModelNotFoundException)
{
abort(404);
}
return parent::render($request, $e);
}
}