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

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

问题描述

我是 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 AppModelEntity;
use CakeORMEntity;

class User extends Entity {

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

UsersController.php(控制器)

namespace AppController;
use AppControllerAppController;

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

在您的情况下,问题是 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天全站免登陆