r/PHPhelp • • Oct 23 '26

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.

3 Upvotes

5 comments sorted by

View all comments

0

u/Special_Bit4460 Oct 23 '26

Disclaimer: I am not familiar with PHPStan and have limited experience with PHP in general.

I am missing a return Type at your getArrayOfObjects method and your targetClass.
The languages I usually work with allow me to do sth like:

abstract class Mapper<T> {

getArrayOfObjects():T[] {

}

}

class BookMapper extends Mapper<Book> {

}

So calling getArrayOfObjects() of a BookMapper will always Return an Array of Books. Your targetClass is currently of the Type string. And your $Book will be mixed So you need a way to add the type to the methods return and/or the targetClass.