不。
不过,如果有帮助的话,可以扩展以前声明的类。
不,从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支持trait。Trait是不能作为独立对象实例化的方法的实现。相反,trait可以用来扩展包含实现的类。在这里了解更多关于Traits的内容。
你也许可以覆盖__call或__callStatic在运行时定位丢失的方法,但你必须创建自己的系统来定位和调用代码。例如,您可以加载一个“Delegate”类来处理方法调用。
这里有一个例子——如果您尝试调用$foo->bar(),该类将尝试创建一个FooDelegate_bar类,并使用相同的参数对其调用bar()。如果你设置了类自动加载,委托可以存在于一个单独的文件中,直到需要…
class Foo {
public function __call($method, $args) {
$delegate="FooDelegate_".$method;
if (class_exists($delegate))
{
$handler=new $delegate($this);
return call_user_func_array(array(&$handler, $method), $args);
}
}
}
是的,可以在PHP类定义之后向其添加方法。您需要使用classkit,它是一个“实验性”扩展。但是,这个扩展在默认情况下是不启用的,所以这取决于你是否可以编译自定义PHP二进制文件或者在windows上加载PHP dll(例如Dreamhost允许自定义PHP二进制文件,而且它们很容易设置)。
<?php
class A { }
classkit_method_add('A', 'bar', '$message', 'echo $message;',
CLASSKIT_ACC_PUBLIC);
$a = new A();
$a->bar('Hello world!');
PHP手册中的示例:
<?php
class Example {
function foo() {
echo "foo!\n";
}
}
// create an Example object
$e = new Example();
// Add a new public method
classkit_method_add(
'Example',
'add',
'$num1, $num2',
'return $num1 + $num2;',
CLASSKIT_ACC_PUBLIC
);
// add 12 + 4
echo $e->add(12, 4);