Daniel Eugen
Daniel Eugen

Reputation: 2780

Creating a new instance of another file

I have a php file called index which is the entry point for my api with the following code

//Entry point...
try {
    echo (new requestHandler($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']))->DoStuff();
} catch (Exception $e) {
    echo json_encode(Array('error' => $e->getMessage()));
}

Then the requestHandler.php handles the request

public function __construct($request)
{
     echo "constructor";
     //do some things
}

However when i call index.php it seems to give an error

PHP Fatal error: Class 'requestHandler' not found in .../index.php

Note: both are separate files...

Upvotes: 1

Views: 244

Answers (1)

Phil
Phil

Reputation: 164913

In this particular case, I suggest you simply add this to the top of your index script...

require_once __DIR__ . '/requestHandler.php';

This is of course assuming the requestHandler class is defined in a file named requestHandler.php.

If you want to try using an autoloader, you need to stick to a convention of class to file names. In your case, it seems like this should suffice (again, in your index script)...

spl_autoload_register(function($class) {
    $path = sprintf('%s/%s.php', __DIR__, $class);
    if (is_readable($path)) {
        require $path;
    }
});

Upvotes: 1

Related Questions