How to import a class in a controller of CakePHP 2

2019-07-08 22:47发布

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

1条回答
狗以群分
2楼-- · 2019-07-08 23:13

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();
查看更多
登录 后发表回答