简体   繁体   中英

PHP Type Hinting when iterate into an object

that's my first post on stackoverflow!

I am developing a PHP framework and I need to provide type hinting on objects.

I'm going to list an example of structure I'm using:

  • a Database class, used as "entry point". This class connects to database using PDO, and has an UserSet property

  • a UserSet class, which extends Set (intended as a collection of users)

  • a Set class with SQL-Like methods
  • a User class, just with Table props

Example

Set has a select method which returns an array of users, via PDO;

$prepare = $this->database->prepare($this->sql);
$prepare->execute();
$prepare->setFetchMode(PDO::FETCH_CLASS,  $this->TABLE);
return $prepare->fetchAll();

UserSet overrides select via @method operator like this:

/** @method User|UserSet select() blablabla */

In this way i get type hinting when assign select to a var

$result = $database->UserSet->select()

but $result is both of type User and UserSet and I have, in the completion code popup (Netbeans), hints from User and UserSet, while I'd like it will be of type UserSet , and have User hints only when iterate. (something like UserSet < User >, thinking like Java)

Is it possible to reach this?

Sorry for the long post! Thank u all!

First of all if your select() method is always returning return $prepare->fetchAll(); then your return type hint in comment @method User|UserSet select() is wrong because PDOStatement::fetchAll() returns an array.

Assuming your $this->TABLE is 'User' then your select() method returns array of User objects. Try hinting it like this: @method User[] select() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM