Search code examples
phpoopautoloader

Class not found PHP OOP


I can't get this to work.

<?php


        function __autoload($classname){
            include 'inc/classes/' . $classname . '.class.php';
        }



__autoload("queries")

$travel = new queries();
echo $travel->getPar("price");

?>

And this is the inc/classes/queries.class.php file.

<?

 class queries {

        function getPar($par, $table='travel', $type='select') {

            $result = $db->query("
             $type *
             FROM $table
             WHERE
             $par LIKE
            ");
            while ($row = $result->fetch_assoc()) {

                return "
                 $row[$par]
                ";
            }

    }
}

?>

It returns "Class 'queries' not found". What's wrong with it?

EDIT:

Fatal error: Cannot redeclare __autoload() (previously declared in /index.php:5) in /index.php on line 5

What the hell? I can't redeclare a function that is already declared in its own line, why?


Solution

  • Instead of that dreadful abomination, you should learn how to utilize spl_autoload_register():

    spl_autoload_register( function( $classname ){
    
        $filename = 'inc/classes/' . $classname . '.class.php';
    
        if ( !file_exists( $filename) ){
            throw new Exception("Could not load class '$classname'.". 
                                "File '$filename' was not found !");
        }
    
        require $filename;
    
    });
    

    And you should register the autoloader in your index.php or bootstrap.php file, and do it only once per loader (this ability lets you define multiple loaders, but that's used, when you have third party library, which has own autoloader .. like in case of SwiftMailer).

    P.S. please learn to use prepared statements with MySQLi or PDO.

    Update

    Since you are just now learning OOP, here are few things, which you might find useful:

    Lectures:

    Books: