【问题标题】:Calling a method from AppModel class from its child or Controller从 AppModel 类的子类或控制器调用方法
【发布时间】:2013-12-12 19:18:16
【问题描述】:

你好,这是我的 AppModel.php 类

<?php
App::uses('Model', 'Model');
class AppModel extends Model{


    static public function message()
    {
        return 'this is a message';
    }

}

我有我的模型 User.php

<? 
class User extends AppModel {

}

和我的控制器UsersController.php

class UsersController extends AppController
{
 public function index()
    {
        $this->layout ='main';
}

}

我的问题是,如何在 UsersController 或至少在我的模型用户中从其 AppModel 类调用方法 message()?

【问题讨论】:

  • 你试过 $this->User->message(); ?

标签: php class cakephp inheritance


【解决方案1】:

您可以像使用任何静态方法一样调用它

AppModel::message();

不过,我建议不要将其用作静态。在您的控制器中,当然在您的模型中,您已经拥有一个扩展 AppModel 的模型实例。所以如果你改变了

/*static*/ public function message()
{
    return 'this is a message';
}

然后你可以在控制器中调用它

$this->User->message();

在用户模型中使用

$this->message();

当我们使用它时,将其更改为protected,这样只有它的孩子才能使用该功能。

【讨论】:

  • 非常感谢您的回答,您的评论帮助我解决了我的问题和困惑但是当我将方法更改为受保护的函数 message(){...} 我收到此错误错误:SQLSTATE [ 42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“消息”附近使用正确的语法
  • 啊,这意味着您的模型无法识别该函数并将其解释为 SQL。您在哪里以及如何称呼它?
  • 我在我的 usercontroller.php 中调用它 public function index() { echo $this->User->message(); }
猜你喜欢
  • 2013-12-20
  • 2016-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 2011-06-26
相关资源
最近更新 更多