Search code examples
phpoopencapsulationautoload

Set __autoload to use a private function of a class


I have a class with a private function that i don't want to be called directly.

Example class:

class Importer{
    private function import(){}
}

Now i want to send a parameter passed to __autoload() to import function of Importer class.
I also know regularly is impossible and illogical to call a private function but do you know any solution or trick to keep import() private or preventing direct access ?


Solution

  • class Importer {
        public function __construct() {
            spl_autoload_register( array($this, 'import') );
        }
    
        private function import($class) {
            include $class . '.php';
        }
    }
    
    $importer = new Importer();
    
    $obj = new testclass();
    
    var_dump($obj);
    

    Output

    object(testclass)#2 (0) { }