Class not found PHP OOP

江枫思渺然 提交于 2019-12-25 08:53:11

问题


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?


回答1:


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:

  • Advanced OO Patterns
  • Inheritance, Polymorphism, & Testing
  • Recognizing smelly code
  • Global State and Singletons
  • Don't Look For Things!

Books:

  • PHP Object-Oriented Solutions
  • Patterns of Enterprise Application Architecture



回答2:


Try so (without class autoload):

function __autoload($classname){
    include_once 'inc/classes/' . $classname . '.class.php';
}
$travel = new queries();

Also see this link




回答3:


remove this line from you code __autoload("queries"), you don't need to call autoloader it will be called by it self whenever it encounters any undeclared class and use require_once instead of include and debug if you paths are correct or not.



来源:https://stackoverflow.com/questions/11375225/class-not-found-php-oop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!