0

Using Laravel, I'm iterating through a series of classes and doing an operation on a subset of instances of each class. The classes are provided as strings, eg:

$c = '\App\Models\Book';

$c::each(function($i) {
    echo $i->title . PHP_EOL;
});

How would I type hint $i?

Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99
  • Do all classes share a common interface? Or a common parent class? Without knowing more about these classes, it's pretty difficult to tell you what to add – Nico Haase Dec 18 '21 at 21:31
  • @NicoHaase they all extend the standard `Illuminate\Database\Eloquent\Model` – Adam Hopkinson Dec 18 '21 at 22:24
  • But not all of them have a `title` field? Then I don't see any possibility to add a proper type hint – Nico Haase Dec 19 '21 at 10:26
  • 2
    if they are all models then you could type hint `Model`, but you don't need a type hint at all, especially since you are most likely accessing dynamic properties (attributes, relationships) of the model any way, which are not actually defined on any model instance any way – lagbox Dec 19 '21 at 16:08
  • 1
    What is the purpose of type hinting here? What benefit will you achieve by type hinting? If it’s to allow your IDE to pickup details, there are plugins which do this for you (in phpstorm) – Savlon Dec 19 '21 at 21:06
  • Thanks all. This was more of a thought excercise, based on Psalm flagging a notice/info for an equivalent situation. I know that I don't have to type hint, I was merely interested as to whether it's possible in this situation. – Adam Hopkinson Dec 19 '21 at 21:44

1 Answers1

0

You can type it as object{title:string}, if you sure about title and wants to tell about it to paslm.

Also, maybe you may find useful conditional types - https://psalm.dev/docs/annotating_code/type_syntax/conditional_types/

Anton
  • 728
  • 3
  • 8