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

时光总嘲笑我的痴心妄想 提交于 2019-11-26 18:29:07

问题


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

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)

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

回答1:


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

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.

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!



来源:https://stackoverflow.com/questions/31813722/what-means-call-to-a-member-function-on-boolean-and-how-to-fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!