Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

I guess i did not learn my fundamentals on php classes that well, but I would appreciate some help here.

I have been getting this error: Fatal error: Call to a member function myFunction() on a non-object ...

Basically i have a php class file with functions in it that works.

In my main file, I have instantiated the class and can call class functions successfully by
$myNewClassObject->myFunction("source");

However, I need to do some automation here so I happily put the line above into another new function in the main file like this:
function repeat()
{
   $myNewClassObject->myFunction("source");
}

Then i call it, also from the main file. This is when I get the error message.
Did i do something wrong, or is this not allowed?

I mean i could just do it in a more primitive way instead of a function, but i'm also curious in cases where I want to create a function, to call my class functions.

Sorry, hope my explanation's not too confusing.

Brian
Posted
Updated 25-Mar-11 23:35pm
v4

Do I take it myNewClassObject is part of your class? And repeat is not? So how can it access class instance objects? More repeat into your class definition, and all should be well...
 
Share this answer
 
When you instantiate $myNewClassObject in the main file, you are doing it in the global scope. This means that the body of your repeat function doesn't have access to it. You can do either of the following:

1. Declare $myNewClassObject as global:
PHP
function repeat()
{
   global $myNewClassObject;
   $myNewClassObject->myFunction("source");
}



2. Make your entire main file into a class itself, with $myNewClassObject as a member variable which you can then access via $this->myNewClassObject. This avoids having globals which can get a little messy with large scripts.
 
Share this answer
 
Comments
Albin Abel 26-Mar-11 8:15am    
Good answer
Variables defined in your main program aren't visible inside functions by default. You must either pass the object as a parameter or declare the variable as global inside the function.
See: http://www.php.net/manual/en/functions.arguments.php[^]
http://www.php.net/manual/en/language.variables.scope.php[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900