php global causing non-object error unless transfered from $GLOBALS

I have a file that contains a class. I will include this file when I need access to the class. I want to declare the class inside the file where the class exists, so that I only have to declare the class once, and only have to include the file to use the class.

This works.

<?php

$GLOBALS['foo_model'] = new foo_model;
$foo_model = $GLOBALS['foo_model'];
global $foo_model;

Class foo_model
{
    function foo_function() {
        // ect
    }
}

This does not work

<?php

$foo_model = new foo_model;
global $foo_model;

Class foo_model
{
    function foo_function() {
        // ect
    }
}

It causes the error when the class is attempted to be used.

Call to a member function foo_function() on a non-object

Why do I have to start with $GLOBALS, and then turn it into a regular variable and then apply global. I thought $GLOBALS and global were only different in syntax. What does $GLOBALS do differently here?

Furthermore, what is the best way to write a file that contains a class, so that I can include the file, and use the class, without having to declare the class after including the file, and without using $GLOBALS? Is my first code snippet the best way to accomplish this?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s