#Strongly Type Class Strings in Methods
8 messages · Page 1 of 1 (latest)
Natively as a type, not that I'm aware of. Would it be so bad to have an immediate validation/exception in the constructor where you assert the class exists and the given class extends model and implements interface. Like a value object would
That's the direction I've been leaning. I was just hoping there was a more elegant solution. Especially since in this case I'm looking for an intersection type so I have to do multiple checks
public function __construct(public string $model) {
if (
!is_a($model, Illuminate\Database\Eloquent\Model::class, true) ||
!is_a($model, App\Contracts\CustomInterface::class, true)
) {
throw new InvalidArgumentException;
}
}
just seems kind of ugly but it works. I'm surprised that is_a and instanceof don't work with intersection or union types. Seems like it should with php's stronger emphasis on types these days
@param class-string<Model>
wont throw an error though