【问题标题】:Having trouble getting a PHP class function to use another function in the class无法让 PHP 类函数使用该类中的另一个函数
【发布时间】:2014-08-11 19:52:50
【问题描述】:

在我的 PHP 文件中,我有一个包含所有函数的类,我正在使用这个类与另一个文件进行交互。这是我正在使用的代码:

    public function check_user_exists ($username_original) {
    try {
        $db_connect = SQLConnect(); // Make the PDO handle usable

        // Prepare and fetch the id of the user trying to login, used to validate whether the user exists or not
        $db_interact = $db_connect->prepare("SELECT `id` FROM `users` WHERE `username_raw` = :username_raw");
        $db_interact->bindParam(":username_raw", $username_original);
        $db_interact->setFetchMode(PDO::FETCH_ASSOC);
        $db_interact->execute();
        $db_fetch = $db_interact->fetch();

        if ($db_fetch == false) {    
            return false;
        } else {
            global $validation_code;
            $validation_code = $db_fetch["id"];// Used to log the id of the use0r logging in
            return true;
        }
    } catch (PDOException $e) {
        echo $e->getMessage; // Used if something goes wrong with the PDO statement
    }
}

这是一个使用 PDO 来检查数据库中是否存在用户的简单函数。

正如您在第三行代码中看到的,该函数引用了SQLConnect()。当我使用函数check_user_exists() 时,它给了我一个致命错误,说我调用了一个未定义的函数,除了SQLConnect() 在同一个文件中,并且在同一个PHP 类中。

这是SQLConnect()

    // Function to allow database interactions
public function SQLConnect () {
    // Database connection variables
    $host = "localhost";
    $dbname = "dropbox-database";
    $user = "root";
    $password = "password";
    // Set connect to null
    static $connect = null;

    if (is_null($connect)) {
        try {
            // Database connection variables
            $host = "localhost";
            $dbname = "dropbox-database";
            $user = "root";
            $password = "ethan17458";
            // Initiate connection
            $connect = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
            // Set error mode
            $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
        } catch (PDOException $e) {
            // If there is an error, echo error message
            echo $e->getMessage();
        }
        // Make $connect usable
        return $connect;
    }
}

我正在使用这个函数通过 PDO 打开一个数据库连接。

当这两个函数在同一个文件中并且在同一个类中时,为什么会触发一个致命错误?我该如何解决这个问题?

谢谢,

伊森

【问题讨论】:

  • 因为类中的函数是类的方法,而不是全局可访问的函数。您可以通过 $this->SQLConnect() 访问它
  • 谢谢!我试过了,效果很好。
  • 我发布了一个答案,所以你可以接受它

标签: php mysql oop pdo


【解决方案1】:
$db_connect = SQLConnect(); 

应该是

$db_connect = $this->SQLConnect(); 

因为类中的函数是类的方法,不能全局访问。使用 $this-> 告诉 PHP 在类中定位方法。应该注意$this 意味着更多,但这是针对您当前问题的简洁解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 2014-03-16
    • 2021-06-05
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    相关资源
    最近更新 更多