2

I apologise for the unclear title, I cannot think of any better one. I'm getting this error:

Fatal error: Call to a member function query() on a non-object

This is caused by the constructor in a class SPConfig, which can be seen together with a class SPClasses as follows:

$sp = new SPClasses();

class SPClasses
{
    public $db, $config, $page, $users;

    function __construct()
    {       
        // The SPDatabase class [...]
        $this->db = new SPDatabase();

        // The SPConfig class [...]
        $this->config = new SPConfig();

        // [...]

        // The SPTemplate class [...]
        $this->page = new SPTemplate();

        // The SPUsers class [...]
        $this->users = new SPUsers();
    }
}

class SPConfig
{
    function __construct()
    {
        global $sp;
        $configquery = $sp->db->query("SELECT * FROM config", 'Retrieving the configuration');
        while($row = mysql_fetch_array($configquery))
        {
            try
            {
                $this->{$row['name']} = $row['value'];
            }
            catch (Exception $e)
            {
                $debug_log[] = array(
                    'type' => 'error',
                    'success' => false,
                    'text' => 'The config setting <i>' . $row['config_value'] . '</i> has an invalid name.'
                );
            }
        }
    }


    public function update()
    {
        $this->__construct();
    }
}

Does anyone know why it is impossible for me to access $sp->db in the SPClasses constructor?

Thanks.

tereško
  • 58,060
  • 25
  • 98
  • 150
unrelativity
  • 3,670
  • 6
  • 38
  • 63

2 Answers2

4

Until $sp is constructed and assigned, it doesn't have a value. Thing is, the constructor tries to create a SPConfig, which attempts to access the still-null $sp.

In order for this to work, the constructor will need to pass either $this or $this->db to the SPConfig constructor.

cHao
  • 84,970
  • 20
  • 145
  • 172
3

You have a chicken-egg problem. While assigning the global $sp you instanciate the SPClassesobject which instanciates SPCOnfig which accesses $sp which is not assigned yet.

Pass the SPClasses object as a parameter to the SPConfig class and you are fine.

ZeissS
  • 11,867
  • 4
  • 35
  • 50