php反射调用失败

hwjfshx 2008-09-16 05:33:50
<?php
/**
* A counter class
*/
class Counter{
private $ss = 'dd';
private $dd = 'ss';
public $o = 'o';

public function getSs(){
return $this -> ss;
}
public function getO(){
return $this -> o;
}
public function getDd(){
return $this -> dd;
}
}

$ct = new Counter();
echo invoke($ct, getMethod('ss'));
function getMethod($fieldName){
return 'get' . ucfirst($fieldName);
}
function invoke($obj, $methodName){
$reflector = new ReflectionObject($obj);
$method = $reflector -> getMethod($methodName);
return $method -> invoke(null); //反射调用有问题。。。
}
?>
直接echo $method有内容
但最后一句$method -> invoke(null)运行时就出错了
Fatal error: Uncaught exception 'ReflectionException' with message 'Non-object passed to Invoke()' in C:\Program Files\AppServ\www\guestbook\index.php:54 Stack trace: #0 C:\Program Files\AppServ\www\guestbook\index.php(54): ReflectionMethod->invoke(NULL) #1 C:\Program Files\AppServ\www\guestbook\index.php(47): invoke(Object(Counter), 'getSs') #2 {main} thrown in C:\Program Files\AppServ\www\guestbook\index.php on line 54

我传进去的是已经实例化的对象。参照PHP文档的调用方法写的。
网上搜了很久,没有搜到答案。
请高人指点
...全文
285 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
hwjfshx 2008-09-17
  • 打赏
  • 举报
回复
非常感谢
原来是类似JS的函数指针来用

不过,PHP参考手册上能够用ReflectionMethod的invoke方法来调用
还是不理解。手册上传的用的是ReflectionClass,我用ReflectionObject而已。。。
cheryc666 2008-09-16
  • 打赏
  • 举报
回复

<?php
/**
* A counter class
*/
class Counter{
private $ss = 'dd';
private $dd = 'ss';
public $o = 'o';

public function getSs(){
return $this -> ss;
}
public function getO(){
return $this -> o;
}
public function getDd(){
return $this -> dd;
}
}

$ct = new Counter();
echo invoke($ct, getMethod('ss')); //输出dd
function getMethod($fieldName){
return 'get' . ucfirst($fieldName);
}
function invoke($obj, $methodName){
/*$reflector = new ReflectionObject($obj);
$method = $reflector -> getMethod($methodName);
return $method -> invoke(null); //反射调用有问题。。。 */
return $obj ->$methodName(null);
}
?>
cheryc666 2008-09-16
  • 打赏
  • 举报
回复

<?php
/**
* A counter class
*/
class Counter{
private $ss = 'dd';
private $dd = 'ss';
public $o = 'o';

public function getSs(){
return $this -> ss;
}
public function getO(){
return $this -> o;
}
public function getDd(){
return $this -> dd;
}
}

$ct = new Counter();
echo invoke($ct, getMethod('ss')); //输出dd
function getMethod($fieldName){
return 'get' . ucfirst($fieldName);
}
function invoke($obj, $methodName){
/*$reflector = new ReflectionObject($obj);
$method = $reflector -> getMethod($methodName);
return $method -> invoke(null); //反射调用有问题。。。 */

return $obj ->$methodName(null);
}
?>

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧