1

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 will 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

CMS scripting
  • 669
  • 1
  • 7
  • 13
  • 1
    The problem isn't the included file - the problem is that you are calling a function, which isn't in class scope anymore (the included file by itself is). – NikiC Jun 18 '11 at 16:47
  • 2
    Private is private. If you need to call it outside the class, it has to be public. Or make it protected and extend a subclass to which `otherFunction()` belongs – Michael Berkowski Jun 18 '11 at 16:49
  • I too encourage that you pay attention to both comments given above. – Melsi Jun 18 '11 at 17:18

1 Answers1

2

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.

Charles Sprayberry
  • 7,741
  • 3
  • 41
  • 50