EHerman
EHerman

Reputation: 1892

Call to undefined method. Can't figure out why

I have set up a class with a few functions in it. I've included a seperate php file into the main one. I have a few public functions set up, all which are working. I just went to add a new one, and its throwing an error and I can't figure out why.

if(!class_exists("classBase"))
    {
  class classBase
        {

         public function printName()
         { 
          $name = 'Test Name!';
          return $name;
         }  

  }
}

I'n my separate file that is included into this one, I am trying to call this function as I am all my other functions in the file.

<?php $this->printName(); ?>

I tried declaring the function before and after the file is included, But for whatever reason, this is throwing the error: Fatal error: Call to undefined method classBase::printName()

I even tried copying a working function, appending a number to the function name, and calling that new function. But still throwing an error. I'm confused as to why its not working.

Upvotes: 0

Views: 643

Answers (2)

EHerman
EHerman

Reputation: 1892

Face Palm

So damn embarassing...

I have two localhost test sites set up. I was editing the class file on the site I wasn't testing, and adding the call to the function into the site I was testing. Therefore it was throwing the error and it was correct, the method was never defined.

Just spent 45 minutes wondering what I was doing wrong...

Clearly I need to step away from the computer and go on lunch.

Upvotes: 0

Andresito
Andresito

Reputation: 143

You need to initialize an instance of that class. In your example:

if(!class_exists("classBase"))
{
  class classBase
  {

         public function printName()
         { 
          $name = 'Test Name!';
          return $name;
         }  

  }
}

$myInstance = new classBase();

$myInstance->printName();

Upvotes: 3

Related Questions