PHP OOP: Unique method per argument type?

跟風遠走 提交于 2019-12-01 21:13:54

It is acceptable to have a method that delegates to the correct internal method. You could document it like this:

@param Array|User|Integer $argName optional explanation

but then again, there is no one hindering you having one method each

public function getCollectionByRange(array $range)
public function getCollectionByUser(User $user)
public function getCollectionByUserId($id)

In addition, you could use the magic __call method to pretend the above methods exist and then capture method calls to them and delegate to your internal methods (ZF does that f.i. for finding dependant database rows). You would document these methods with the @method annotation in the Class DocBlock. But keep in mind that the magic methods are always slower over having and/or calling the appropriate methods directly.

Use what you think makes most sense for your application and usecase.

You could achieve something like method overloading by checking the type of the passed parameter at runtime (PHP does not support this concept known from other languages like ADA, Java, C# or C++ e.g.):

[...]
/**
 * @param  User|array|integer $user
 * @return array
 */
public function getCollection($user) {
    // perhaps a switch-case would be better here
    if ($user instanceof User) {
        // do what has to be done if you passed in a User object
    } else if (is_int($user) {
        // do what has to be done if you passed in a user id
    } else if (is_array($user)) {
        // do what has to be done if you passed in an array of user ids
    }
}
[...]

It sounds like you want to do function overloading, but PHP (even PHP5) does not do overloading like you would in, say Java. The Overloading section in the PHP manual is not function overloading:

Note: PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.

You might mean this:

class ArticleMapper {
   public function getCollection($param) {
      if (is_array($param)) { $this->getCollectionByArray($param); }
      if (is_int($param)) { $this->getCollectionByInt($param); }
      if (is_a($param, 'User')) { $this->getCollectionByUser($param); }
   }
   private function getCollectionByArray(array $param) { ... }
   private function getCollectionByInt($param) { ... }
   private function getCollectionByUser(User $param) { ... }
}

This seems like the a good way to do it to my eye.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!