gpt4 book ai didi

php - 在 PHP 中定义类方法

转载 作者:可可西里 更新时间:2023-11-01 12:44:12 25 4
gpt4 key购买 nike

是否有可能在 PHP(就像在 C++ 中一样) 中声明 类方法 类定义之外?

最佳答案

不,从 PHP 5.2 开始。但是,您可以使用 __call 魔术方法将调用转发到任意函数或方法。

class A {

public function __call($method, $args) {
if ($method == 'foo') {
return call_user_func_array('bar', $args);
}
}

}

function bar($x) {
echo $x;
}

$a = new A();
$a->foo('12345'); // will result in calling bar('12345')

在 PHP 5.4 中支持traits。 Trait 是无法实例化为独立对象的方法的实现。相反,trait 可用于通过包含的实现来扩展类。了解有关特征的更多信息 here .

关于php - 在 PHP 中定义类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71478/

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