0

I'm trying to understand why this isnt working, as I am new to PHP I havent come up with a solution.

Background: I have a DB connection class (Works fine). I want to clean up my code by creating the DB object outside of all of my functions for which I can then use it within each (Instead of creating a new DB object for each function). I pull the data in the DB class, then call the needed method in another file of which I can print/display the data.

Heres an example:

THIS DOES NOT WORK: It produces: Fatal error: Call to a member function getProductsOnSale() on a non-object

require("DB.class.php");
include_once 'functions.php';
$db = new DB();

function displaySalesProducts(){
    $salesProduct = $db->getProductsOnSale();
    //STUFF METHOD DOES
}

However, this DOES work

require("DB.class.php");
include_once 'functions.php';

function displaySalesProducts(){
    $db = new DB();
    $salesProduct = $db->getProductsOnSale();
    //STUFF METHOD DOES
}

I'm looking for some insight as to why exactly this is happening as I dont have a great grasp of php yet. Thanks!

user3344880
  • 11
  • 1
  • 7
  • 1
    You need to add `global $db;` at the beginning of the function body if you want to use it as a global variable. However this is not recommended because it could get messy. The recommended way is to pass the `$db` variable to the function as an argument. See the duplicate answer that I added above. – Cave Johnson Mar 10 '16 at 01:05
  • function is being called in a different file so this doesnt help much, I dont understand why it needs to be declared global just to use it. – user3344880 Mar 10 '16 at 01:07
  • It was probably done this way so local variables don't get mixed up with global variables. You have to explicitly label them as global variables. Can you not require the `DB.class.php` file in the file that is calling this function and initialize the `$db` object there? – Cave Johnson Mar 10 '16 at 01:10
  • Yeah I'm able to do that, I was hoping I could get away with keeping the object out of that file though. I guess this will have to do, thanks for the help! – user3344880 Mar 10 '16 at 01:13

0 Answers0