找不到类PHP OOP [英] Class not found PHP OOP

查看:79
本文介绍了找不到类PHP OOP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用它.

<?php


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



__autoload("queries")

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

?>

这是inc/classes/queries.class.php文件.

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?

致命错误:无法在第5行的/index.php中重新声明__autoload()(先前在/index.php:5中声明)

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?

推荐答案

您应该学习如何利用

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;

});

并且您应该在index.phpbootstrap.php文件中注册自动加载器,并且每个加载器仅执行一次(此功能可让您定义多个加载器,但是当您拥有第三方库时使用该库autoloader ..就像SwiftMailer一样).

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.请学习将准备好的语句与MySQLi或PDO一起使用.

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

更新

由于您现在正在学习OOP,因此以下几件事可能会有用:

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

讲座:

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

书籍:

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

这篇关于找不到类PHP OOP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆