Why can't I overload constructors in PHP?

后端 未结 14 905
长情又很酷
长情又很酷 2020-12-04 11:30

I have abandoned all hope of ever being able to overload my constructors in PHP, so what I\'d really like to know is why.

Is there even a reason for it? Doe

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 11:45

    You can of course overload any function in PHP using __call() and __callStatic() magic methods. It is a little bit tricky, but the implementation can do exactly what your are looking for. Here is the resource on the official PHP.net website:

    https://www.php.net/manual/en/language.oop5.overloading.php#object.call

    And here is the example which works for both static and non-static methods:

    class MethodTest
    {
        public function __call($name, $arguments)
        {
            // Note: value of $name is case sensitive.
            echo "Calling object method '$name' "
                 . implode(', ', $arguments). "\n";
        }
    
        /**  As of PHP 5.3.0  */
        public static function __callStatic($name, $arguments)
        {
            // Note: value of $name is case sensitive.
            echo "Calling static method '$name' "
                 . implode(', ', $arguments). "\n";
        }
    }
    
    $obj = new MethodTest;
    $obj->runTest('in object context');
    
    MethodTest::runTest('in static context');  // As of PHP 5.3.0
    
    

    And you can apply this to constructors by using the following code in the __construct():

    $clsName = get_class($this);
    $clsName->methodName($args);
    

    Pretty easy. And you may want to implement __clone() to make a clone copy of the class with the method that you called without having the function that you called in every instance...

提交回复
热议问题