douhun8647 2013-09-01 16:59 采纳率: 0%
浏览 45
已采纳

从另一个函数调用公共函数

I have a database class with several PDO functions inside (db.inc.php). I'm trying to call this function from another function:

// Query method
public function query($query) {
    $this->stmt = $this->dbh->prepare($query);
}

In my global PHP file I have instantiated the database using:

// Instantiate database
$database = new database();

However when trying to call this function from another function inside of a different PHP file (user.inc.php):

function confirmAccount($key,$id) {
// Check key and id against entry in database
$database->query('SELECT * FROM users WHERE id = :id');
}

I get the following error:

Fatal error: Call to a member function query() on a non-object in /home/studevne/public_html/includes/user.inc.php on line 10

All of my PHP files are included in the global PHP file as so:

include_once 'includes/db.inc.php';
include_once 'includes/echo.inc.php';
include_once 'includes/tools.inc.php';
include_once 'includes/user.inc.php';

I'm guessing its something to do with the scope of the database class and its functions howevver I'm a little confused on how to solve this. Any help is greatly appreciated.

  • 写回答

1条回答 默认 最新

  • dongxing8009 2013-09-01 17:04
    关注

    You need to pass $database into the function, else it's out of scope. You can either pass it in as a parameter:

    function confirmAccount($key,$id,$database) {
        // Check key and id against entry in database
        $database->query('SELECT * FROM users WHERE id = :id');
    }
    

    Or as a global:

    function confirmAccount($key,$id) {
        global $database;
        // Check key and id against entry in database
        $database->query('SELECT * FROM users WHERE id = :id');
    }
    

    globals are generally frowned upon, as they make it very easy to write messy code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思