PHP OOP: Unique method per argument type?

前端 未结 3 677
谎友^
谎友^ 2021-01-20 06:44

I\'m writing a little homebrew ORM (academic interest). I\'m trying to adhere to the TDD concept as a training exercise, and as part of that exercise I\'m writing documentat

3条回答
  •  温柔的废话
    2021-01-20 07:41

    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.

提交回复
热议问题