N
N
newProgrammer20172018-02-15 10:42:13
PHP
newProgrammer2017, 2018-02-15 10:42:13

How to properly autoload the parent class?

Good afternoon. Help please deal with the problem. I am autoloading classes. The structure is as follows, at the root of the site there is index.php in it, using require (), the file with the config.php settings is connected and below the creation of an instance of the Post class.

require('./config.php');
$post = new \Vendor\Blog\Post();

In config.php there are settings for connecting to the database, the project_autoload() class autoload function and its registration via spl_autoload_register(). The included classes are located in /lib/Vendor/Blog/ relative to the site's root folder.
function project_autoload($className)
{
    $className = ltrim($className, '\\');
    $fileName  = $_SERVER['DOCUMENT_ROOT'].'/lib/';
    $namespace = '';
    if ($lastNsPos = strrpos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    require_once($fileName);
}

The DB.php class contains the following code:
namespace Vendor\Blog\DB;

class DB
{
//code
}

The Post.php class contains the following code:
namespace Vendor\Blog\Post;
use Vendor\Blog\DB;

class Post extends DB
{
     //code
}

Gives an error message:
Fatal error: Class 'Vendor\Blog\DB' not found in ....../public_html/lib/Vendor/Blog/Post.php on line 7

Line 7, this is the line with the bracket { at the beginning:
class Post extends DB
{
     public $id;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
newProgrammer2017, 2018-02-15
@newProgrammer2017

Thanks for the reply, the answer was given on another resource:

namespace is incorrectly specified, in both classes.
In your case, the namespace should be Vendor\Blog;
And already in use, specify both the namespace and the class name.
andkorol,

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question