PHP function overloading

前端 未结 10 983
北恋
北恋 2020-11-22 17:24

Coming from C++ background ;)
How can I overload PHP functions?

One function definition if there are any arguments, and another if there are no arguments? Is it

10条回答
  •  不知归路
    2020-11-22 17:31

    Sadly there is no overload in PHP as it is done in C#. But i have a little trick. I declare arguments with default null values and check them in a function. That way my function can do different things depending on arguments. Below is simple example:

    public function query($queryString, $class = null) //second arg. is optional
    {
        $query = $this->dbLink->prepare($queryString);
        $query->execute();
    
        //if there is second argument method does different thing
        if (!is_null($class)) { 
            $query->setFetchMode(PDO::FETCH_CLASS, $class);
        }
    
        return $query->fetchAll();
    }
    
    //This loads rows in to array of class
    $Result = $this->query($queryString, "SomeClass");
    //This loads rows as standard arrays
    $Result = $this->query($queryString);
    

提交回复
热议问题