什么是PHP函数重载? [英] What is PHP function overloading for?
问题描述
在Java之类的语言中,可以通过以下方式使用重载:
In languages like Java, overloading can be used in this way:
void test($foo, $bar){}
int test($foo){}
然后,如果您使用2个参数(例如test($x, $y);
)调用了test()
,则将调用第一个函数.如果仅传递了1个参数,例如test($x);
,则将调用第二个函数.
Then if you called test()
with 2 arguments e.g test($x, $y);
, the first function would be called. If you passed only 1 argument e.g test($x);
, the 2nd function would be called.
从手册中看来,php 5确实有重载,但是它的作用是什么?我似乎无法理解有关此主题的手册.
From the manual it seems that php 5 does have overloading, but what is it for? I can't seem to understand the manual on this topic..
推荐答案
PHP的重载含义与Java的不同.在PHP中,重载意味着您可以通过实现
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.
PHP中的重载提供了以下方法: 动态地创建"属性并 方法.这些动态实体是 通过魔术方法可以处理 建立各种课程 动作类型.
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.
一个例子:
class Foo
{
public function __call($method, $args)
{
echo "Called method $method";
}
}
$foo = new Foo;
$foo->bar(); // Called method bar
$foo->baz(); // Called method baz
顺便说一句,自PHP 4.3.0起,PHP就支持这种重载.唯一的区别是,在PHP 5之前的版本中,您必须使用
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.
这篇关于什么是PHP函数重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!