包括类而不必重新定义

时间:2015-03-26 04:51:47

标签: php

所以我知道为了在b.class.php中使用a.class.php,我需要在b类文件中包含一个类。我的问题是这个。 我的网站平台目前有两个类文件。 db.class.php和account.class.php

db.class.php

<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/settings.php');
class db extends pdo{
    //Website Variables

    public $sitedb = '';
    public $siteconfig;
    public $sitesettings = array(
        'host'      => SITEHOST,
        'database'  => SITEDB,
        'username'  => SITEUSER,
        'password'  => SITEPASS,
    );
    public $realmdb = '';
    public $realmconfig;
    public $realmsettings = array(
        'host'      => REALMHOST,
        'database'  => REALMDB,
        'username'  => REALMUSER,
        'password'  => REALMPASS,
    );

    public function __construct(){

        $this->sitedb = new PDO(
            "mysql:host={$this->sitesettings['host']};" .
            "dbname={$this->sitesettings['database']};" .
            "charset=utf8",
            "{$this->sitesettings['username']}",
            "{$this->sitesettings['password']}"
        );
        $this->realmdb = new PDO(
            "mysql:host={$this->realmsettings['host']};" .
            "dbname={$this->realmsettings['database']};" .
            "charset=utf8",
            "{$this->realmsettings['username']}",
            "{$this->realmsettings['password']}"
        );
        $this->sitedb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        $this->realmdb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    }

}
$db = new db();

account.class.php

<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/settings.php');
class account extends db {
    public function Login() {
        $query = <<<SQL
        SELECT id
        FROM profile
        WHERE password = :password
SQL;
            $resource = $db->sitedb->prepare ( $query );
            $resource->execute( array(
                ':password' => sha1(strtoupper($_POST['email'].':'.$_POST['password'],
                ));
                $row_count = $resource->rowCount();
                echo $row_count;

        }
}
$account = new account();

此当前格式告诉我无法重新定义db,但是如果我删除了包含

的设置文件的要求
foreach (glob("functions.d/*.class.php") as $class)
{
    include $class;
}

然后告诉我无法找到类db。我可以通过哪种方式正常工作?

1 个答案:

答案 0 :(得分:0)

事实证明,实现这一目标的最佳方法是正确保留包含并将所有类放在同一个文件中,并且在我的包含页面中使用类具有全局$ db或global $ account,具体取决于我调用的类功能