So i have this class that includes some custom functions named class.php I have another file called config.php that includes
require('engine.class.php');
$engine = new engine;
config.php also requires 开发者_运维知识库functions.php to run like:
require('functions.php');
i have a function in functions.php that uses $engine eg:
function login($username, $password){
return $engine->mysql_query('SELECT `user_id` WH...', 'array);//this is custom function in class.php
}
but when i run the page that reuires config.php i get some error like:
Fatal error: Call to a member function mysql_query() on a non-object in ../somedir/functions.php on line 3
Global variables are indisputably evil. Any one who tells you to use them does not have scope experience in dealing w/ code that uses them. Unfortunately, there are far more PHP coders using globals than any other language, in my experience, largely due to ignorance.
Virtually every class should be self-consistent, meaning that it shouldn't matter how many times you substantiate it into an object via new. The only exception is the Singleton pattern, but real-world instances where singletons are desirable are so rare that virtually every use of those is also an uncalled design flaw that just tightly couples code, which is also a very bad thing.
PHP caches DB connections, so you can have an unlimited mysql_connect()s in the same program and it will only connect once per page load (unless you manually close it). So remove the $engine from your config.php immediately and rewrite all your code to this:
function login($username, $password)
{
$engine = new Engine;
//this is custom function in class.php
return $engine->mysql_query('SELECT `user_id` WH...', 'array);
}
I'll happily elucidate more, if you need it.
You will need to refer to Variables scope. As you cannot access $engine without it being global or defining / declaring it (singleton design pattern comes to mind) inside the function.
EDIT
You could also pass it as a parameter to the function (previously forgot to mention this).
精彩评论