php 调用布尔成员函数是什么意思以及如何修复

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31813722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:38:18  来源:igfitidea点击:

What means Call to a member function on boolean and how to fix

phpmodel-view-controllercakephp-3.0

提问by CodeWhisperer

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".

我是 cakePHP 3 的新手。我创建了一个控制器和模型,我在其中调用了一个函数来从数据库中获取所有用户。但是当我运行下面的代码时,我会收到以下错误“Call to a member function get_all_users() on boolean”

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

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

User.php (model)

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 (controller)

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());
    }
}

回答by ndm

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

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

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 falseon error, and that's where it happens, you will be calling a method on a boolean.

与控制器名称匹配的表不需要手动加载/设置为属性,但即使它们最初不存在,尝试访问它们会导致调用控制器魔法 getter 方法,用于延迟加载表类它属于控制器,它false在错误时返回,这就是它发生的地方,您将在布尔值上调用一个方法。

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

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.

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

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

你的自定义方法应该放在一个表类中,而不是UsersTable你应该通过访问的类

$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!

您可能想重新阅读文档,实体不查询数据(除非您例如实施延迟加载),它们代表一个数据集!