Jump to content

[SOLVED] Member function on a non-object within a function! ($this-> syntax)


Dale_G

Recommended Posts

Hello everyone, right so I am including an external file as such...

 

require( 'members.php' );

 

And I've confirmed it works, using this syntax everything is fine.

 

echo $members->show('all');

 

It shows all of the members, it does what it is supposed to do. However, when I throw it into a function and attempt to call the function, as shown below...

 

function show_members()
{
    echo $members->show('all');
}

show_members();

 

It does not work and throws a "Fatal error: Call to a member function on a non-object" error, and I know why. I can remedy this problem by adding "global $members;" to the function, like this.

 

function show_members()
{
    global $members;

    echo $members->show('all');
}

 

So now, the completed working file is shown below.

 

require( 'members.php' );

function show_members()
{
    global $members;

    echo $members->show('all');
}

 

show_members();

 

And that's fine. However as I develop this project there will be MANY choices that require different calls to different functions, so I will be making over 30 functions similar to show_members(), that call different functions under the $members class.

 

Basically, what I'm wondering is if there is a way to "globally" declare the $members class. So I don't have to type "global $members;" in each function...as that can get rather bothersome the more functions I add.

 

Also, I will probably throw this into a class later on, so if there is a way to globally declare it for the class, that would be awesome. :)

It's not generally a good idea to declare things as global in functions.  You'd be better off passing the object around or making a Registry (some purists will protest, but it gets the job done).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.