Search code examples
joomlajoomla2.5joomla-extensions

Joomla 2.5 cant use $this in helper file


I have created a component and a plugin in joomla 2.5 and there is a Helper file in the component which will have many useful functions and I plan to call one of its function which then calls another function in the helper by this code:

$this->getinformation();

and it gives me this error :

Fatal error: Call to undefined method

My questions are:

  • Why can't I call a function in a helper in Joomla?
  • How can I call a function inside helper class?
  • Is there any class structure which i missed in this code?

Solution

  • Helper files are typically called statically and not using $this

    First create your helper file and add methods like this:

    Class myHelper {
    
        //This method can call other methods
        public static function myMethod($var) {
    
            //Call other method inside this class like this:
            self::myOtherMethod($var);
    
        }
    
        //This method is called by myMethod()
        public static function myOtherMethod($var) {
    
            //Put some code here
    
        }
    
    }
    

    Simply include the helper file like this in the documents that you would to use it:

    require_once JPATH_COMPONENT.'/helpers/my_helper.php';
    

    Then use it like this:

    myHelper::myMethod($var);
    

    or

    myHelper::myOtherMethod($var);