views:

36

answers:

2

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
+2  A: 

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).

Brad F Jacobs
Or passing it to the function.
Felix Kling
In 12 years of PHP programming, I have **never** come across the need for a global, despite using them heavily when I first started out.Just ... don't ... do it!
hopeseekr
I never suggested using `globals`, just stated that it is a method available for use. The user can read up on `globals` if he wants and decide whether or not he wants to use them, his choice, even if they are not the best method. My preference would be the singleton method or the parameter, depending on the usage / need.
Brad F Jacobs
+1  A: 

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.

hopeseekr
Thank you, i guess this is better!
tazphoenix