CakePHP控制器自定义函数无法识别


CakePHP controller custom function not recognized

我正在学习CakePHP并遵循本教程。

在实现DELETE控件时,我决定创建一个自定义函数来包含一些重复的代码行。然而,当我尝试调用它时,我的自定义函数无法识别。

我的代码如下:

class PostsController extends AppController{
public $helpers = array('Html', 'Form');
public function index(){
    $this->set('posts', $this->Post->find('all'));
}//index
public function view($id = null){
    if(!$id){
        throw new NotFoundException(__('Invalid Post'));
    }
    $post = $this->Post->findById($id);
    if(!$post){
        throw new NotFoundException(__('Invalid Post'));
    }
    $this->set('post', $post);
}//view
public function add(){
    if($this->request->is('post')){
        $this->Post->create();
        if($this->Post->save($this->request->data)){
            $this->Session->setFlash(__('Your post has been saved.'));
            return $this->redirect(array('action'=>'index'));
        }
        $this->Session->setFlash(__('Unable to add your post.'));
    }
}//add
public function edit($id=null){
    idCheck($id);
    $post = $this->Post->findById($id);
    if(!$post)
        throw new NotFoundException(__('Invalid post'));
    if($this->request->is(array('post', 'put'))){
        $this->Post->id = $id;
        if($this->Post->save($this->request->data)){
            $this->Session->setFlash(__('Your post has been updated!'));
            return $this->redirect(array('action'=>'index'));
        }
        $this->Session->setFlash(__('Unable to update your post.'));
    }
    if(!$this->request->data)
        $this->request->data = $post;
}//edit
public function delete($id=null){
    idCheck($id);
}
public function idCheck($id=null){
    if(!$id)
        throw new NotFoundException(__('Post ID required'));
    if(!is_numeric($id))
        throw new NotFoundException(__('Post ID must be numeric'));
}
}

我所要做的就是调用我的idCheck()函数,但我得到了这个错误:

错误:调用未定义的函数idcheck()

在cakepp中,不能直接调用函数。

看看你在玩对象,如果你想调用属于当前对象的函数,请使用

$this->Your_function();

根据您的问题,使用:

$this->idCheck($id);

表示对当前对象调用函数idCheck()函数。