What is PHP function overloading for?

前端 未结 3 1326
死守一世寂寞
死守一世寂寞 2020-12-24 03:08

In languages like Java, overloading can be used in this way:

void test($foo, $bar){}
int test($foo){}

Then if you called test()

3条回答
  •  没有蜡笔的小新
    2020-12-24 03:44

    PHP's meaning of overloading is different than Java's. In PHP, overloading means that you are able to add object members at runtime, by implementing some of the __magic methods, like __get, __set, __call, __callStatic. You load objects with new members.

    Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.

    An example:

    class Foo
    {
        public function __call($method, $args)
        {
            echo "Called method $method";
        }
    }
    
    $foo = new Foo;
    
    $foo->bar(); // Called method bar
    $foo->baz(); // Called method baz
    

    And by the way, PHP supports this kind of overloading since PHP 4.3.0. The only difference is that in versions prior to PHP 5 you had to explicitly activate overloading using the overload() function.

提交回复
热议问题