Search code examples
ideautocompletecommentsphpdocdocblocks

How to set the @return value of a dynamic function?


Say I have this function:

function load_model($modelName)
{
   $model = new $modelName;
   return $model;
}

Using it, I can do:

$userModel = load_model('user');
$forumModel = load_model('forum');

etc. Both will be different models with different classes, different functions, etc.

However, my autocomplete doesn't work, because it doesn't know what the return value of the load_model() function is going to be.

Is there any way to do something like this?

/**
* @return $modelName
*/

That will tell the IDE that the returning value is a user model class, or a forum model class?


Solution

  • No... the best you can hope for here is that if your various kinds of model classes all implement the same interface, or perhaps all extend from the same abstract parent class, you can put the interface or abstract class name as the return type.

    Examples:

    If

    class UserModel implements ModelInterface {}

    Then your load_model() function can

    @return ModelInterface an object that implements a Model

    ...

    Or, if

    class UserModel extends ModelAbstractParent {}

    Then your load_model() function can

    @return ModelAbstractParent a concrete Model object

    ...

    There's just no other way for phpDocumentor to decipher a return type that is dynamic at runtime, and therefore there's no way for an IDE's autocomplete to figure it out either.

    However, if your various concrete model classes do properly implement a top-level interface or extend from a common abstract parent class, then using the interface/abstract as the return type will allow for some level of autocomplete to work in the IDE.

    EDIT: there is one other way to document the return type, but I still don't think autocomplete will work by using it -- listing multiple return types:

    @return UserModel|LoadModel|PlaneModel|TrainModel|AutomobileModel an object of one of the various model classes