user936965
user936965

Reputation:

When to use `use` or the fully qualified name

I'm wondering when to use the fully qualified class name or when to put a use statement on top of the class. For example:

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' );
    }
}

At the moment I have this piece of code and my PHPStorm tells me Unnecessary fully qualified name. This hint disappears when I change it to:

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' );
    }
}

So I'm wondering what the difference is, performance wise, code readability and if one is better than the other.

Upvotes: 5

Views: 1478

Answers (1)

Justinas
Justinas

Reputation: 43479

When you do use SomeNamespace\ClassName than you do not have later append \SomeNamespace to ClassName. So your example should be

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' );
    }
}

Please note that when you are in same namespace, than you do not need to add namespace to class name. When namespace App; then User::class instead of \App\User::class

Upvotes: 1

Related Questions