如:
interface A {
public function test();
}class B {
public function test(){
echo 'test me!';
}
}//B实现A接口
class_implements('B', 'A');请问不用eval有办法实现吗?
我参考了一些有关reflection的文档,并未发现能动态的“实现"某个接口的方法,望高人指教,谢谢!
?>
interface A {
public function test();
}class B {
public function test(){
echo 'test me!';
}
}//B实现A接口
class_implements('B', 'A');请问不用eval有办法实现吗?
我参考了一些有关reflection的文档,并未发现能动态的“实现"某个接口的方法,望高人指教,谢谢!
?>
$classname::test(); //这样吗?
call_user_func_array是动态调用方法的接口;我现在想要【动态地让B类实现A接口】的方法,事先B类与A接口毫无关系。谢谢!
但不用php_rpc和nusoap来实现。
返璞归真
{
function __call($name,$param)
{
$interface=_class_implements(get_class($this),'',(string)$this);
if(is_array($interface)){
foreach($interface as $iface){
if(method_exists($iface,$name)){
return call_user_func_array(array($iface,$name),array_merge(array($this),$param));
}
}
}
}
}
function _class_implements($class,$interface='',$class_id='')
{
static $struct,$instance;
if($interface){
if($struct[$class][$interface]) return;
$struct[$class][$interface]=1;
if(is_array($instance[$class])){
foreach($instance[$class] as $k=>$v){
if(!$instance[$class][$k][$interface])
$instance[$class][$k][$interface]=new $interface;
}
}
}else{
if(!$instance[$class][$class_id]){
if(is_array($struct[$class])){
foreach($struct[$class] as $k=>$v)
$instance[$class][$class_id][]=new $k;
}
}
return $instance[$class][$class_id];
}
}/******************************分割线******************************/
class_implements是保留字无法使用,上面的函数名只好在前面加下划线使用方法:
1.类不可以实现__toString方法。
2.将上面的__call手动加入类里,或简单的以base作为基类。
3.所有interface都写成class,并在每一个成员方法的第一个参数$_this来代替$this/******************************分割线******************************/举例:
//interface A
class A {
public function test($_this)
{
echo "test me.";
}
}//interface C
class C {
public function whoAmI($_this,$msg)
{
echo $msg.$_this->myName;
}
}//class B
class B extends base{
}_class_implements('B', 'A');
_class_implements('B', 'C');$b=new B;
$b->myName='jazzard';
$b->test();
$b->whoAmI('my name is ');//结果得到输出"test me.my name is jazzard";