使用Cakephp 3的虚拟字段

使用Cakephp 3的虚拟字段,php,cakephp,orm,cakephp-3.0,Php,Cakephp,Orm,Cakephp 3.0,我需要在我的用户实体中有一个虚拟财产。我跟着火车走 UserEntity.php namespace App\Model\Entity; use Cake\ORM\Entity; class User extends Entity { protected $_virtual = ['full_name']; protected function _getFullName() { return $this->_properties['firstname

我需要在我的用户实体中有一个虚拟财产。我跟着火车走

UserEntity.php
namespace App\Model\Entity;

use Cake\ORM\Entity;

class User extends Entity {

    protected $_virtual = ['full_name'];

    protected function _getFullName() {
        return $this->_properties['firstname'] . ' ' . $this->_properties['lastname'];
    }
}
在控制器中

namespace App\Model\Entity;

use Cake\ORM\Entity;

class User extends Entity {

    protected $_virtual = ['full_name'];

    protected function _getFullName() {
        return $this->_properties['firstname'] . ' ' . $this->_properties['lastname'];
    }
}
$users = TableRegistry::get('Users');
$user = $users->get(29);
$firstname = $user->firstname; // $firstname: "John"
$lastname = $user->lastname; // $lastname: "Doe"
$value = $user->full_name; // $value: null

我严格按照书中的内容操作,只得到了一个
null
值。

根据@ndm,问题是由于文件命名错误。我将用户实体类命名为
UserEntity.php
。他说:

实体类OptionValue可以在名为OptionValue.php的文件中找到


谢谢。

为什么不买这样的东西呢

/*
 * Return Fullname
 */
public function getFullname()
{
    $name = $this->firstname . ' ' . $this->lastname;
    return $name;
}

您确定用户对象中有数据吗?是。只需查看$user->firstname,$user->lastname之后的行注释;请尝试
debug([get\u class($users),get\u class($user)])
,您可能无法对预期的OBEJCT进行操作…@ndm:输出为[(int)0=>'App\Model\Table\UsersTable',(int)1=>'Cake\ORM\Entity']。我想没问题。这意味着找不到
用户
实体类/文件。。。再看一眼,文件名应该是
User.php
,而不是
UserEntity.php
,它必须与类名匹配。虽然这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高文章的质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请编辑您的答案,添加解释,并说明适用的限制和假设。