Nikk
Nikk

Reputation: 7891

Class Extends wont work in include_once()

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?

Upvotes: 0

Views: 340

Answers (2)

Chin Leung
Chin Leung

Reputation: 14921

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.


1. Manual load

main.php

<?php

require __DIR__ . '/ClassC.php';
new ClassC();

ClassA.php

<?php

class ClassA{

    public function __construct(){
        echo 'Hello World.';
    }

}

ClassB.php

<?php

require __DIR__ . '/ClassA.php';

class ClassB extends ClassA{

}

ClassC.php

<?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.

2. Autoload (without namespace)

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

main.php

<?php

require __DIR__ . '/autoload.php';
new ClassC();

ClassA.php

<?php

class ClassA{

    public function __construct(){

        echo 'Hello World';

    }

}

Note: The ClassA is the same as the other example.

ClassB.php

<?php

class ClassB extends ClassA{

}

ClassC.php

<?php

class ClassC extends ClassB{

}

Note: The ClassB and ClassC no longer has the require at the top of the file.

autoload.php

<?php

spl_autoload_register(function($class){

    $path = __DIR__ . '/' . $class . '.php';

    if(file_exists($path))
        require $path;

});

Breakdown of autoload.php

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.

Upvotes: 1

mllec
mllec

Reputation: 22

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.

Upvotes: 0

Related Questions