Accessing another class' method from within a standalone function [closed]

拈花ヽ惹草 提交于 2019-12-13 09:46:09

问题


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.

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);
}

Returns the error.

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

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?

Thank you,
Joe


回答1:


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

Pass $db as an argument

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

Or

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!




回答2:


$db is out of scope when called from within a function. You could pass $db to the function as an argument

function func($db){

There is also the horribly bad global method:

function func(){
    global $db; // $db is now accessible



回答3:


Learn about variable scope. The variable $db is not declared inside the function, so it does not exist inside the function. You need to pass it in.




回答4:


Oooh, you have initiated $db as a global :/

There are a lot of reasons why you would not want to do this and I will not go into this here primarily because I am a tad short on time, I will await the purists to comment below. But a quick fix is to add.

global $db

Not the most ideal situation ever but should solve your issue.



来源:https://stackoverflow.com/questions/13932191/accessing-another-class-method-from-within-a-standalone-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!