#Strongly Type Class Strings in Methods

8 messages · Page 1 of 1 (latest)

rotund hinge
#

Does anyone know of a good way/resource to strongly type class strings? I've got this set up:

public function __construct(public string $model) {
}

and I want to make sure that the string that is passed is an instance of Illuminate\Database\Eloquent\Model&App\Contracts\CustomInterface

livid dock
#

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

rotund hinge
#

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

granite matrix
#

@param class-string<Model>

tame valve
#

wont throw an error though

livid dock
#

Outside of static blocks yea

#

I have no issue with your above Cole

#

I don't know if php will ever have native types for class strings, simply because they are strings. I'm happy we got the ::class constant on objects, so who knows, maybe a future rfc