Search code examples
cakephpcakephp-2.0cakephp-2.1

How to import a class in a controller of CakePHP 2.0?


I am using CakePHP. I created an external class which is not a model nor a controller. The structure of the class looks like this

class UploadImage{
    function sayHello(){
       return "hahaha";
   }
}

I saved the class in the App->Lib directory and named it as UploadImage.php

I wanted to call the method sayHello() in my controller which is:

class ContentsController extends AppController {

    public $helpers = array('Html', 'Form');

    public function index() {
        $test = App::uses('UploadImage','Lib');
        debug($test->sayHello());
    }
}

Now when I run the above page, I get the following error:

Error: Call to a member function sayHello() on a non-object


Solution

  • App::uses() is a statement you place at the beginning of the file

    you still have to program in php5 - meaning that you have to use new!

    App::uses('UploadImage','Lib');
    class ContentsController extends AppController {}
    

    and in your method:

    $test = new UploadImage();