开发者

PHP custom class loader

开发者 https://www.devze.com 2023-01-22 18:28 出处:网络
i made a custom 开发者_StackOverflow中文版class loader function in php something like.. load_class($className,$parameters,$instantiate);

i made a custom 开发者_StackOverflow中文版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;
}


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


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.

0

精彩评论

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

关注公众号