在PHP类中包含另一个文件 [英] Include another file in PHP class

查看:154
本文介绍了在PHP类中包含另一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信这已被问过几次,但我似乎无法找到一个直截了当或解释清楚的答案。我正在尝试在PHP中创建一个帐户对象/类,我可以从帐户中检索数据。我遇到的问题是我不能包含我的database.php类,所以我可以检索所有创建的帐户。

I'm sure this has been asked a few times, but I can't seem to find a straight forward or well explained answer. I'm attempting to create a Account Object/Class within PHP, where I can retrieve data from an account. The issue I'm having is that I cannot include my database.php class so I can retrieve all the created accounts.

我对PHP很新,并且对大量流程或约定的工作方式没有广泛的了解。我遇到的错误/警告是这样的;

I'm fairly new with PHP and don't have an expansive knowledge on how a lot of the processes or conventions work. The error/warning I'm running into is this;


警告:include(../ database.php):无法打开流:没有这样的文件
或第3行〜/ account.php中的目录

Warning: include(../database.php): failed to open stream: No such file or directory in ~/account.php on line 3

这是我的account.php类

Here is my account.php class

<?php

include '../database.php';

class Account {

    protected $username, $email;

    protected function getEmail() {
        return $this->email;
    }

    protected function getUsername() {
        return $this->username;
    }

    public function __construct($username, $email) {
        $this->username = $username;
        $this->email = $email;
    }

    public static function getUser($username) {
        $statement = getConnection()->prepare('SELECT * FROM account WHERE username=?');
        $statement->bindValue(1, $username);

        if ($rows = $statement->fetch()) {
             $account = new Account($rows['username'], $rows['email']);
        }

         return $account;
    }

}

这是我的database.php incase我做错了什么或者可能需要更改东西

Here is my database.php incase I've done something wrong or may need to change things

<?php

function getConnection() {
    $dbh = new PDO("mysql:host=127.0.0.1;dbname=mcsl;port3306", "root", "");
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    return $dbh;
}

目录结构:

推荐答案

您可以使用 include(dirname( __FILE __)。/../ database.php)访问account.php文件中的database.php文件

You can use include (dirname(__FILE__)."/../database.php") to access the database.php file in the account.php file

这篇关于在PHP类中包含另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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