views:

45

answers:

2

i made a custom class loader function in php something like..

load_class($className,$parameters,$instantiate);

its supposed to include the class and optionally instantiate the class specified

the problem is about the parameters. ive been trying to pass the parameters all day i tried

load_class('className',"'param1','param2'",TRUE);

and

load_class('className',array('param1','param2'),TRUE);

luckily nothing works xD is it possible to pass the params? i even tried..

$clas = new MyClass(array('param1','param2'));

here it is..

function load_class($class, $param=null, $instantiate=FALSE){
    $object = array();
    $object['is_required'] = require_once(CLASSES.$class.'.php');
    if($instantiate AND $object['is_required']){
        $object[$class] = new $class($param);
    }
    return $object;
}
A: 

Seems to me that you should be using __autoload() to just load classes as they are referenced and circumvent having to call this method manually. This is exactly what __autoload() is for.

Craige
A: 

if you are in PHP 5.x I really really recommend you to use autoload. Prior to PHP 5.3 you should create sort of "namespace" (I usually do this with _ (underscore))

autoload allows you to include classes on the fly and if your classes are well designed the overhead is minimun.

usually my autoload function looks like:

<?php
function __autoload($className) {
    $base = dirname(__FILE__);
    $path = explode('_', $className);

    $class = strtolower(implode('/',$path));

    $file = $base . "/" . $class;       

    if (file_exists($file)) {
        require $file;      
    }
    else {
        error_log('Class "' . $className . '" could not be autoloaded');
        throw new Exception('Class "' . $className . '" could not be autoloaded from: '.$file); 
    }
}

this way calling

$car = new App_Model_Car(array('color' => 'red', 'brand' => 'ford'));

the function will include the class

app/model/car.php

Gabriel Sosa