从独立函数中访问另一个类的方法 [英] Accessing another class' method from within a standalone function

查看:114
本文介绍了从独立函数中访问另一个类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将我的网站转换为PDO,在大约200个脚本后,我非常接近结束。每个脚本访问相同的函数脚本。在函数脚本中我有一个数据库类,看起来像这样:

I am converting a my site to PDO and after about 200 scripts I am very near the end. Every script accesses the same functions script. Within the functions script I have a Database class which looks like so:

class Database {
    private $db_con = ''; //stores the connection

    public function db_login(){
        //log into the database
    }
    public function db_control($query, $params){
        //run the query
    }
}
//initiate the class and log in
$db = new Database();
$db->db_login();

这两个函数都适用于每种类型的查询,因此我几乎完成了。但是,我遇到了一个问题。

Both of these functions work fine and for every type of query, hence why I am almost finished. However, I have run into a problem.

我在脚本中有一个独立的函数,我在脚本中使用了多次。我通常运行db_control:

I have a standalone function on a script I am working on which is used several times within the script. I usually run the db_control:

$results = $db->db_control($query, $params);

但是从一个函数中运行它:

But running it from within a function:

function func(){
    $results = $db->db_control($query, $params);
}

返回错误。


致命错误:调用
上的非对象的成员函数db_control()C:.... php第39行

Fatal error: Call to a member function db_control() on a non-object in C:....php on line 39

我做错了什么?该类肯定是启动作为脚本上的其他查询工作正常,当此功能删除。如何从独立函数中访问db_control()?

What am I doing wrong? The class is definitely being initiated as other queries on the script work fine when this function is removed. How can I access db_control() from within a standalone function?

谢谢

Joe

Thank you,
Joe

推荐答案

$ db 在函数范围内不可用,可以

$db is not available within the function scope, you could

通过 $ db 作为参数

function func($db, $query, $params){
    return $db->db_control($query, $params);
}
$results = func($db, $query, $params);

function func($query, $params){
    global $db;
    return $db->db_control($query, $params);
}
$result = func($query, $params);

使用全局功能,可能还有其他解决方案!

Use global to make it available within the function, there's probably other solutions too!

这篇关于从独立函数中访问另一个类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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