从包含文件调用私有或受保护的方法


Call private or protected method from an include file

myclass.php

class myclass {
private $name;
public function showData(){
    include_once "extension.php";
    otherFunction($this);
}
private function display(){
    echo "hello world!";
}
}

extension.php

function otherFunction($obj){
    if(isset($obj){
   $obj->display();
    }
}

好吧,这就是问题所在,对你们中的一些人来说,我从包含文件中调用一个私有方法显然会引发错误,这是显而易见的。我的问题是:

1.是否有一种方法可以将包含文件可以使用外部函数调用私人方法

2.如何使用包含的文件访问私有方法并通过执行因此将我的函数扩展到另一个文件而不制作我的类文件有很多功能吗

3.这可能吗

感谢

如果您使用的是PHP 5.3,这是可能的。

它被称为反射。根据您的需求,您需要ReflectionMethod

http://us3.php.net/manual/en/class.reflectionmethod.php

这里有一个的例子

<?php
//  example.php
include 'myclass.php';
$MyClass = new MyClass();
//  throws SPL exception if display doesn't exist
$display = new ReflectionMethod($MyClass, 'display');
//  lets us invoke private and protected methods
$display->setAccesible(true);
//  calls the method
$display->invoke();
}

显然,您需要将其封装在try/catch块中,以确保异常得到处理。