PHP报错Call to undefined method UserEntity::setIdUser()排查
问题原因
报错Call to undefined method UserEntity::setIdUser()的核心原因是setIdUser()、getIdUser()方法被定义在了UserEntity类的闭合花括号外部,不属于UserEntity类的成员方法,类实例无法调用。
你贴出的UserEntity代码里,类在属性定义完成后就直接用}闭合了,后续写的两个方法本质是全局函数,和UserEntity类没有任何绑定关系。而且这两个全局函数内部直接使用$this,本身就不符合PHP语法——全局作用域不存在$this上下文,就算直接调用这两个全局函数也会抛出错误。
除此之外你还漏写了setEmail()、setSexe()、setFirstname()、setLastname()这几个方法,就算修复了setIdUser()的定义位置,后续调用其他setter时依然会抛出相同的未定义方法错误。
修复步骤
- 把所有getter、setter方法移动到
UserEntity类的花括号内部 - 为所有类方法添加
public访问修饰符(实体类的读写方法需要对外可访问) - 补全所有属性对应的setter、getter方法
修复后的完整UserEntity类代码如下:
class UserEntity{ protected $idUser; protected string $email; protected ?int $sexe; protected ?string $firstname; protected ?string $lastname; public function getIdUser() { return $this->idUser; } public function setIdUser($idUser) { $this->idUser = $idUser; return $this; } public function getEmail() { return $this->email; } public function setEmail($email) { $this->email = $email; return $this; } public function getSexe() { return $this->sexe; } public function setSexe($sexe) { $this->sexe = $sexe; return $this; } public function getFirstname() { return $this->firstname; } public function setFirstname($firstname) { $this->firstname = $firstname; return $this; } public function getLastname() { return $this->lastname; } public function setLastname($lastname) { $this->lastname = $lastname; return $this; } }
替换原有UserEntity类代码后重新访问即可解决报错。
内容的提问来源于stack exchange,提问作者Frédéric Lafleur
相关产品推荐
相关产品推荐

