Jump to content

php class autoload question


Go to solution Solved by kicken,

Recommended Posts

okay, so here is my question in regards to this autoload script.  

So let's say my files in my classes folder is hello.class.inc and my class is defined as

 

class Hello{
     //some code here
}
	

So I noticed in a file where I call upon class such as

$var = new Hello();

I would get an error saying "Hello.class.php" doesn't exist

but if I rename the class with a capital H in Hello.class.php it will work. 

So what is going on here that causes that?

 

<?php
spl_autoload_register('myAutoLoader');
	function myAutoloader ($className){
    $url = $SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	    if(strpos($url, 'includes' ) !== false) {
        $path = '../classes/';
    }
    else {
        $path = 'classes/';
    }
	$extension = '.class.php';
	require_once $path . $className . $extension;
}
?>
	
Edited by jcarney1987
Link to comment
https://forums.phpfreaks.com/topic/317127-php-class-autoload-question/
Share on other sites

My suggestion is to use composer https://getcomposer.org/ as it will save you a lot a headaches and you don't have to reinvent the wheel.

Then you can just do something like the following ->

<?php
// Include the configuration file and autoload file from the composer.
require_once __DIR__ . '/../config/config.php';
require_once "vendor/autoload.php";

// Import the ErrorHandler and Database classes from the PhotoTech namespace.
use brainwave\{
    ErrorHandler,
    Database,
    Links,
    ImageContentManager,
    LoginRepository as Login
};

// Instantiate the ErrorHandler class
$errorHandler = new ErrorHandler();

// Set the exception handler to use the handleException method from the ErrorHandler instance
set_exception_handler([$errorHandler, 'handleException']);

// Create a new instance of the Database class
$database = new Database();
// Create a PDO instance using the Database class's method
$pdo = $database->createPDO();

$login = new Login($pdo);
if ($login->check_login_token()) {
    header('location: dashboard.php');
    exit();
}

$cms = new ImageContentManager($pdo);

a sample class ->

<?php
// ErrorHandler.php
namespace brainwave;

use PDOException;
use Throwable;
use JsonException;

class ErrorHandler implements ErrorHandlerInterface
{
    public function handleException(Throwable $e): void
    {
        if ($e instanceof PDOException) {
            error_log('PDO Error: ' . $e->getMessage());
        } elseif ($e instanceof JsonException) {
            error_log('JSON Error: ' . $e->getMessage());
        } else {
            error_log('General Error: ' . $e->getMessage());
        }
    }
}

I would also check out namespace for PHP classes.

Edited by Strider64
  • Like 1
14 hours ago, jcarney1987 said:

So what is going on here that causes that?

Some filesystems are case-sensitive, so Hello.class.php and hello.class.php are two completely separate files. You need to either ensure you are using the correct case when creating and referencing your files, or normalize the case in some way (such as making everything lowercase).

 

  • Like 1

so I guess I don't understand the internals of spl_autoload_register.

So if I call for

Class Hello {
    //some code here
}

it looks for the file based on class name.  I was thinking it slurps up the class directory searching for the class then including it. 

  • Solution
1 hour ago, jcarney1987 said:

so I guess I don't understand the internals of spl_autoload_register

There are no internals of spl_autoload_register with regards to the locating and loading of a class.  All the details of how that is done is up to the function you provide.  All spl_autoload_register does is add your function to a list of functions that get called when an unknown class is referenced.  Your function gets the fully qualified name of the class and has to use that to define that class, typically by converting the name to a file location and including that file.

Your example essentially just uses the class name as-is as a file path and attempts to include that file.  Since your class is defined as Hello then you get a filename of Hello.class.php with a capital H.  Your actual filename however seems to be hello.class.php with a lower-case H.  On a case-insensitive filesystem such as windows' ntfs, this would be fine and the file would be loaded.  On a case-sensitive filesystem such as linux ext4, this is a problem and the file will fail to load.

As mentioned, typically one would just use composer to handle class autoloading rather than defining your own function.  Combine it with the PSR-4 standard (and ensure you get your case correct) and you mostly don't have to think about it at all.

  • Like 1

Yes, I do use Linux as my Base system and I plan on using Linux and FreeBSD as my base WebServers.   Composer does sound great in the long run, right now I'm more concerned with learning and understanding the language better before I break off and start learning package managers and frameworks.  It's all good stuff.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.