Reputation: 5
I'm a new PHP deveploper and I'm having a bad time with the autoload function. This is the error.
public class dog{ public function hey($var){ echo $var; } }
Fatal error: Uncaught Error: Class 'dog' not found in C:\xampp\htdocs\ebay\index.php:3 Stack trace: #0 {main} thrown in C:\xampp\htdocs\ebay\index.php on line 3
It shows the class but then echo a error.
This is the autoload function.
require_once("config.php");
spl_autoload_register("my_auto_load");
function my_auto_load($class_name){
$path = "classes";
require_once($path.DS.$class_name.".php");
}
And this is the index file
require_once("config.php");
spl_autoload_register("my_auto_load");
function my_auto_load($class_name){
$path = "classes";
require_once($path.DS.$class_name.".php");
}
And this is the index file
<?php
require_once("inc/autoload.php");
$dog= new dog();
$dog->hey("KLK");
?>
Upvotes: 0
Views: 134
Reputation: 6955
There are a few things you could do to track down your problem. Try updating your autoload function to look like this:
function my_auto_load($class_name){
$path = "classes";
$includeFilename = $path.DS.$class_name.".php";
?>
Class: <?= $class_name; ?><br>
Include Filename: <?= $includeFilename; ?><br>
Include Filename Real Path: <?= realpath($includeFilename); ?><br>
Current working directory: <?= getcwd(); ?><br>
Does the include file exists? <?= file_exists($includeFilename) ? "Yes, it exists" : "No, it doesn't exist"; ?><br>
<?php
require_once($includeFilename);
}
This will show you whether your autoload function is even running, and if it is running, what file it's actually trying to include and whether that file exists. If it's creating the filepath correctly and the file exists, then your problem is likely somewhere else.
I re-created your project and it seems to work fine. This is my directory structure:
./classes/dog.php
./inc/autoload.php
./index.php
index.php
<?php
require_once("inc/autoload.php");
$dog= new dog();
$dog->hey("KLK");
inc/autoload.php
<?php
spl_autoload_register("my_auto_load");
function my_auto_load($class_name){
$path = "classes";
$includeFilename = $path.'/'.$class_name.".php";
?>
Class: <?= $class_name; ?><br>
Include Filename: <?= $includeFilename; ?><br>
Include Filename Real Path: <?= realpath($includeFilename); ?><br>
Current working directory: <?= getcwd(); ?><br>
Does the include file exists? <?= file_exists($includeFilename) ? "Yes, it exists" : "No, it doesn't exist"; ?><br>
<?php
require_once($includeFilename);
}
classes/dog.php
<?php
class dog {
public function hey($msg) {
echo $msg;
}
}
Upvotes: 2