Jump to content

Class autoloading


AdRock

Recommended Posts

I have recently started using OOP for my old procedural code and I'm getting the hang of it.

 

The problem I have is with autoloading my class files.

 

I have this code on each of my pages I'm redoing.

 

require("php/classes/dbConstants.php");


function __autoload($className) {
$extensions = array(".php", ".class.php", ".inc");
$paths = explode(PATH_SEPARATOR, get_include_path());
$className = str_replace("_" , DIRECTORY_SEPARATOR, $className);
foreach ($paths as $path) {
$filename = $path . DIRECTORY_SEPARATOR . $className;
foreach ($extensions as $ext) {
if (is_readable($filename . $ext)) {
require_once $filename . $ext;
break;
  }
  }
}
}


try {
$forum = new Database(DBHOST, DBUSER, DBPASS, DBNAME);
}
catch (Exception $e) {
echo $e->getMessage(), "\n";
}

but i'm getting this error message

 

Fatal error: Class 'Database' not found in C:\www\newOB\news.php on line 21

 

 

The file with the autoloader is in the root and the database class is in a folder called php and in a subfolder called classes.

 

I need to adjust the path of where it's looking for my classes but no idea how

 

Can anyone please help?

Link to comment
https://forums.phpfreaks.com/topic/281780-class-autoloading/
Share on other sites

I would choose a single naming convention for my class files.

Then I can.......

function __autoload($className) {

     include $path_to_class_directory . '/' . $className . '.class.php';
}

Anyways, You can (if you insist) .......

function __autoload($className) {
     $extensions = array(".php", ".class.php", ".inc");
     $paths = explode(PATH_SEPARATOR, get_include_path());
     
     # #########################################
     // ADD CLASSES DIR TO THE $paths ARRAY
     # #########################################
     $paths[] = '/documentRoot/php/classes';

     $className = str_replace("_" , DIRECTORY_SEPARATOR, $className);
     foreach ($paths as $path) {
         $filename = $path . DIRECTORY_SEPARATOR . $className;
         foreach ($extensions as $ext) {
              if (is_readable($filename . $ext)) {
                    require_once $filename . $ext;
                    break;
              }
         }
     }
}
Link to comment
https://forums.phpfreaks.com/topic/281780-class-autoloading/#findComment-1447809
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.