0

Im new to OOP in PHP. I just can't extend a class from an external file. They are both on the same folder.

DB.php

<?php

class DB {
   // some functions here
}

Home.php

<?php
require_once("DB.php");
class Home extends DB {
   // initialize db and some functions here
}

and I get an error: Fatal error: Class 'DB' not found in \location\to\Home.php on line 3

4
  • You must require the file first. Commented Dec 21, 2017 at 2:27
  • 1
    You must require with absolute path. require_once __DIR__ . '/DB.php'; Commented Dec 21, 2017 at 2:32
  • I update the question. It required the file just forgot to add to the question. I'm still getting the error. Commented Dec 21, 2017 at 2:32
  • Thank you @zerkms, It worked. Please add your comment to answer. Commented Dec 21, 2017 at 2:39

1 Answer 1

4

It should be an absolute path import

require_once __DIR__ . '/DB.php';

Why: because otherwise the relative import is evaluated relatively to your current working directory, which is basically can be anything during the runtime. So it's recommended to always require files with the absolute path.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.