何时使用`use`或完全限定名称

时间:2017-07-05 09:38:56

标签: php namespaces

我想知道何时使用完全限定的类名或何时在类的顶部放置use语句。 例如:

namespace App;

use Illuminate\Database\Eloquent\Model;

class ImageStatus extends Model {
    public function image(): \Illuminate\Database\Eloquent\Relations\BelongsTo {
        return $this->belongsTo( \App\Image::class, 'id' );
    }

    public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo {
        return $this->belongsTo( \App\User::class, 'id' );
    }
}

目前我有这段代码而我的PHPStorm告诉我Unnecessary fully qualified name。当我将其更改为:

时,此提示会消失
namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ImageStatus extends Model {
    public function image(): BelongsTo {
        return $this->belongsTo( \App\Image::class, 'id' );
    }

    public function user(): BelongsTo {
        return $this->belongsTo( \App\User::class, 'id' );
    }
}

所以我想知道差异是什么,性能明智,代码可读性以及一个是否优于另一个。

1 个答案:

答案 0 :(得分:0)

当您执行use SomeNamespace\ClassName时,您将\SomeNamespace添加到ClassName namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class ImageStatus extends Model { public function image(): BelongsTo { return $this->belongsTo(Image::class, 'id' ); } public function user(): BelongsTo { return $this->belongsTo(User::class, 'id' ); } } 。所以你的例子应该是

namespace App;

请注意,当您处于相同的命名空间时,您不需要将命名空间添加到类名。当User::class然后\App\User::class而不是 private void FindDevice_Executed(object sender, ExecutedRoutedEventArgs e) { var RegisterLowByte = BitConverter.GetBytes(infoRegisters[j])[0]; var hasItem = sdb.GetProductFilteredWithLinq(RegisterLow); if (hasItem != null) { foreach (var item in hasItem) { lb_Configuration.Items.Add(item); } } else { ... } }