开发者

Call private or protected method from an include file

开发者 https://www.devze.com 2023-03-13 17:49 出处:网络
myclass.php class myclass { private $name; public function showData(){ include_once \"extension.php\"; otherFunction($this);

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();
    }

}

Ok, so this is the issue, for some of you it is obvious that I am calling a private method from an include file which obviously wi开发者_StackOverflow中文版ll throw an error. My question is:

1. Is there a way that an include file can use external functions to call private methods?

2. How could I use an included file to access private methods and by doing so extending my functions to another file without making my class file so bloated with many functions?

3. Is that even possible?

Thanks


If you're working with PHP 5.3 yes this is possible.

It's called Reflection. For your needs you want ReflectionMethod

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

Here's an example

<?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();

}

Obviously you'll want to wrap this in a try/catch block to ensure the exception gets handled.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号