tomexsans
tomexsans

Reputation: 4527

How to Detect the Variable used to initialize a class

I have this simple autoloading script, the only problem is that I do not know what variable my class1 is initialized. I var_dump the variable $class and it says

object(class1)[1]

But when I tried to $class->someMethod() variable class is undefined?

on my ClassLib Directory I have a

-class1.php and -class2.php

My COde:

function init_load($class){ 
include 'ClassLib/'.$class.'.php'; 
}

function verify_fclass($class){
if(!file_exists('ClassLib/'.$class.'.php')){
    return FALSE;
}else{
    if(!class_exists($class)){
        return FALSE;
    }else{
        return TRUE;
    }
}

}

function init_classes($classes = array()){
foreach($classes as $class){
    if(verify_fclass($class) === FALSE){
        $test[$class.'NotExisting'] = $class;
    }else{
             $test = null;
             $class = new $class;
    }
}
var_dump($class); // what is on class
var_dump($test);  // what is on test
}

$class_array = array('NonExistingClass','class1');
spl_autoload_register('init_load');
init_classes($class_array);

$class->what();

Upvotes: 0

Views: 86

Answers (1)

Louis Huppenbauer
Louis Huppenbauer

Reputation: 3714

You still have to define the class instance $class outside of the function scope.

That means you should return $class in your init_classes function. The only problem I see here is that you want to be able to instantiate several classes at once so you might have to return an array of classes.

You could try something like this:

function init_classes($classes = array()){
    $error = array();
    $instances = array();

    foreach($classes as $class){
        if(verify_fclass($class) === FALSE){
            $error[$class.'NotExisting'] = $class;
        }
        else{
            $test = null;
            $instances[$class] = new $class;
        }
    }
    return array( 'error' => $error, 'instances' => $instances);
}

$class_array = array('NonExistingClass','class1');
$class = $init['instances']['class1'];
$class->what();

But then again you could just instantiate the class directly without using an array and the init_classes method...

Upvotes: 3

Related Questions