There is a file lorem.php, there is a code in it:

<?php class Header { public static function getData() { $db = Db::getConnection(); 

In this file, everything works fine, database queries are executed. But when I want to get a variable from this file in another:

 <?php include_once('/../models/lorem.php'); $resultid = Header::getData(); 

That gives me an error: Fatal error: Class 'Db' not found in D: \ wamp \ www \ models \ lorem.php

Probably useful information will be that the second file is called by an Ajax request in an html file in another directory. Already tried everything in different varriations, nothing helps ...

    2 answers 2

    Simply, he does not find the file with the class Db.

    You have an import of class Db registered in lorem.php, and the relative path to it is indicated. When you call include, all relative paths of the included file begin to be considered relative to the location of the file IN WHICH it is included.

    Therefore, if you have written in lorem.php

     require 'class/Db.php'; 

    Then when doing

     include_once('/../models/lorem.php'); 

    Db.php is not searched for in /../models/class , but in class/ relative to the main script startup directory.

    Read about automatic class loading.

    • The fact is, the file with the connection to the database is called in front of the controller index.php, using define ('ROOT', dirname ( FILE )); require_once (ROOT. '/ components / Db.php'); The path must be specified for all equally, as far as I understand, from the root of the directory to the file Db.php - Bim Bam
    • @BimBam You describe in full exactly how the call chains occur in both cases. This is a 100% cant with the paths to the class file, and dirname is not always a panacea. - rjhdby

    Always specify absolute paths to files through the constant __DIR__

     require __DIR__ . /classes/db.php include_once(__DIR__ . '/../models/lorem.php');