PHP OOP: Unique method per argument type?

前端 未结 3 654
谎友^
谎友^ 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:37

    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
        }
    }
    [...]
    

提交回复
热议问题