什么是在布尔值上调用成员函数以及如何修复 [英] What means Call to a member function on boolean and how to fix

查看:216
本文介绍了什么是在布尔值上调用成员函数以及如何修复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是CakePHP 3的新手.我创建了一个控制器和模型,在其中我调用了一个函数来从数据库中获取所有用户. 但是,当我运行下面的代码时,会出现以下错误在布尔值上调用成员函数get_all_users()" .

I'm new with cakePHP 3. I have created a controller and model where I call a function to get all users from the database. But when I run the code below I will get the following error "Call to a member function get_all_users() on boolean".

此错误是什么意思,我该如何解决?

what does this error means and how can I fix this up?

User.php(模型)

namespace App\Model\Entity;
use Cake\ORM\Entity;

class User extends Entity {

    public function get_all_users() {
        // find users and return to controller
        return $this->User->find('all');
    }
}

UsersController.php(控制器)

namespace App\Controller;
use App\Controller\AppController;

class UsersController extends AppController {

    public function index() {
        // get all users from model
        $this->set('users', $this->User->get_all_users());
    }
}

推荐答案

通常,当使用控制器的不存在的属性时,会发生此错误.

Generally this error happens when a non-existent property of a controller is being used.

与控制器名称匹配的表不必为 手动加载/设置为属性 ,但是它们最初并不存在,尝试访问它们会导致调用控制器的魔术getter方法,该方法用于延迟加载表类,属于控制器,并且在发生错误时返回false,而这正是发生的地方,您将在布尔值上调用方法.

Tables that do match the controller name do not need to be loaded/set to a property manually, but not even they exist initially, trying to access them causes the controllers magic getter method to be invoked, wich is used for lazy loading the table class that belongs to the controller, and it returns false on error, and that's where it happens, you will be calling a method on a boolean.

https://github .com/cakephp/.../blob/3.0.10/src/Controller/Controller.php#L339

https://github.com/cakephp/.../blob/3.0.10/src/Controller/Controller.php#L339

在您的情况下,问题是User(对于实体为单数)与预期的Users(对于表为复数)不匹配,因此找不到匹配的表类.

In your case the problem is that User (singular, for entities) doesn't match the expected Users (plural, for tables), hence no matching table class can be found.

您的自定义方法应该放在表类中,而不是在UsersTable类中,然后应通过

Your custom method should go in a table class instead, the UsersTable class, which you should then access via

$this->Users

您可能想重新阅读文档,实体不查询数据(除非您例如要实现延迟加载),否则它们表示数据集!

You may want to reread the docs, entities do not query data (unless you are for example implementing lazy loading), they represent a dataset!

这篇关于什么是在布尔值上调用成员函数以及如何修复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆