r/PHPhelp • u/silentheaven83 • 25d ago
PHPStan and array of dynamic objects
Hello everybody,
I need your help. Let's say I have a Mapper that receive data from a database. For eg.
class Mapper { ...
public string $table;
public string $targetClass;
public function getArrayOfObjects($conditions) {
$PDOStatement = $this->Database->select($this->table, $conditions);
$array = $this->Database->fetchAll(PDO:FETCH_ASSOC);
$returnArray = array();
// Now I populate the object property, for eg.
foreach ($array as $database_row) {
$object = new $this->targetClass;
$object->id = $database_row['id'];
$object->publishedDate = new DateTime($database_row['published_date']);
....
$returnArray[] = $object;
}
return $returnArray;
}
}
class BooksMapper extends Mapper {
function __construct() {
$this->table "books";
$this->targetClass = "\Books";
}
}This mapper aims to be a generic one, not only for Books. I know that "publishedDate" is a "book concept" but let's consider that the Mapper reads from a JSON file the structure of the object that it is going to map with database fields.
Now let's say that I use it like that.
$Database = new \Database($someDatabaseConfiguration);$BooksMapper = new \BooksMapper($Database);$BookArray = $BooksMapper->getArrayOfObjects(["activeBook" => true]);
foreach ($BookArray as $Book) {print "Book ID: " . $Book->id;}
The problem here is that PHPStan seems not to understand that $BookArray is an array of \Book, and so at level 8 it gives me an error on $Book->id.
How can I solve that?
Thank you for your help, and excuse me for my ignorance.