我可以在PHP中重载方法吗? [英] Can I overload methods in PHP?
本文介绍了我可以在PHP中重载方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例:
我想拥有两个不同的构造函数,并且我不想使用func_get_arg(),因为那样的话,可能的args是不可见的.
I want to have two different constructors, and I don't want to use func_get_arg(), because then it's invisible what args are possible.
写其中两个是合法的,例如:
Is it legal to write two of them, like:
class MyClass {
public function __construct() {
// do something
}
public function __construct(array $arg) {
// do something
}
}
?
推荐答案
否,但是您可以这样做:
No, but you can do this:
class MyClass {
public function __construct($arg = null) {
if(is_array($arg)) {
// do something with the array
} else {
// do something else
}
}
}
在PHP中,函数可以接收任意数量的参数,如果您给它们提供默认值,则不必定义它们.这样可以伪造"函数重载并允许使用不同的参数访问函数.
In PHP, a function can receive any number of arguments, and they don't have to be defined if you give them a default value. This is how you can 'fake' function overloading and allow access to functions with different arguments.
这篇关于我可以在PHP中重载方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文