php oop call a class within a class [duplicate]
I need help trying to call a class function within another class. Here's my setup:
db.php
class db
{
function connect(){
//db connection code here
}
function query($sql){
//perform query and return results
}
}//end db class
main.php
class main
{
function test(){
$sql = "select * from user";
$result = $db->query($sql);//does not work
}
}//end class
index.php
require_once './db.php';
$db=new database;
$db->connect();
//so far so good
require_once './main.php';
$main=new main;
//r开发者_运维问答est of the code here
The problem is that on index.php I can run $db->query($sql) without any problems, but I can't seem to run them inside the main class, more specifically inside the test function. So if I call $main->test() from index.php I get this error:
Fatal error: Call to a member function query() on a non-object in /path/to/file
Unlike C global variables in PHP are not in the visibility scope of functions/methods, see http://docs.php.net/language.variables.scope
To access global variables you must either import them into the function's scope via global $var
or acccess them through the superglobal $_GLOBAL
But instead of using global variables you might be interested in dependency injection, e.g. (one of many possible ways to implement di):
<?php
$db = new db;
$db->connect();
$main = new main($db);
$result = $main->test();
class db
{
function connect(){
//db connection code here
}
function query($sql){
//perform query and return results
}
}
class main
{
protected $db;
public function __construct($db) {
$this->db = $db;
}
public function test(){
$sql = "select * from user";
return $this->db->query($sql);
}
}
I would add a static getInstance()
method into the Db
class. Then cou can call Db::getInstance()->query(...)
from every scope. You can read more on this pattern on Wikipedia.
Just put:
global $db;
in your test() function.
But if you do this also make sure you check that $db exists and is what you think it is before you use it this way.
I guess you should be using
$db = new db;
because $db is not defined in your main class.
精彩评论