gpt4 book ai didi

PHP 5.3 方法重载(类似于 Java)

转载 作者:可可西里 更新时间:2023-10-31 23:10:13 24 4
gpt4 key购买 nike

在 Java 中,我们有一个方法重载功能,它对单例非常有用。例如,我有两个不同的 getInstance 方法,public static,它们根据收到的参数表现不同:

public static Currency getInstance(String currencyCode)
public static Currency getInstance(Locale locale)

我们可以用 PHP 实现吗?

最佳答案

您可以在运行时确定参数类型:

function getInstance($currency) {
if (is_string($currency)) {
$currency = lookupLokale($currency);
}
// do something with the $currency object
}

在php5.3+(非静态方法的php5.0+)中,也可以使用php的method overloading自己实现类似 Java 的语义。但是,OOP 重载很可能会产生困惑的代码,您应该更喜欢上面的方法内解决方案。

在大多数情况下,如果您只是使用两个不同的方法名称会更清楚。

关于PHP 5.3 方法重载(类似于 Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6582566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com