My file structure is like this:
> main.php
- file1.php
- file2.php
- file3.php
I have a class inside file1.php
:
class ClassFileOne extends OtherClassInSameFile
{
}
that I would like to be used inside file2.php
:
class ClassFileTwo extends ClassFileOne
{
}
However when I do this I get Error: Fatal error: Class 'ClassFileOne' not found in
.
Is there a way to fix this?
At the top of file2.php, you need require_once('path/to/file1.php')
Using require instead of include will cause an error if file1 is not found, so you can easily see if your path is incorrect.
You're getting the error because your file cannot read the other class files.
Let's say this is the file structure:
- root
- main.php
- ClassA.php
- ClassB.php
- ClassC.php
And let's say I want ClassC
to extend ClassB
and ClassB
to extend ClassA
.
<?php
require __DIR__ . '/ClassC.php';
new ClassC();
<?php
class ClassA{
public function __construct(){
echo 'Hello World.';
}
}
<?php
require __DIR__ . '/ClassA.php';
class ClassB extends ClassA{
}
<?php
require __DIR__ . '/ClassB.php';
class ClassC extends ClassB{
}
Notice the require
in the ClassB
and ClassC
. And the result of main.php
would be:
Hello World.
You can create your own autoloader by creating a file (example autoload.php
) and include it in your main. So the file structure will become:
- root
- autoload.php
- main.php
- ClassA.php
- ClassB.php
- ClassC.php
<?php
require __DIR__ . '/autoload.php';
new ClassC();
<?php
class ClassA{
public function __construct(){
echo 'Hello World';
}
}
Note: The ClassA
is the same as the other example.
<?php
class ClassB extends ClassA{
}
<?php
class ClassC extends ClassB{
}
Note: The ClassB
and ClassC
no longer has the require
at the top of the file.
<?php
spl_autoload_register(function($class){
$path = __DIR__ . '/' . $class . '.php';
if(file_exists($path))
require $path;
});
You start by registering your custom autoloader which will take a callable as parameter:
spl_autoload_register(function($class){
});
At this point, if you var_dump($class)
inside the autoloader, you'll get:
ClassC
So with the name of the class, you want to locate the file to load:
$path = __DIR__ . '/' . $class . '.php';
And before loading the file, you want to make sure that the file exists.
if(file_exists($path))
require $path;
If the file doesn't exist, it will simply go to the next autoloader.