PHP7类编写语法错误求助:unexpected '$_perso' (T_VARIABLE)
解决你的PHP类解析错误问题
嘿,我一眼就揪出问题所在啦,咱们一步步来修正:
错误根源
- 方法位置写错了:你把
__getNom这些方法全写到Personne类的大括号外面了!PHP里类的所有方法必须放在类的{}内部,不然PHP会把它们当成独立的全局函数,这时候用$this就会触发语法错误——毕竟$this只有在类的方法里才有意义呀。 - Getter方法写法不对:你的getter根本没必要传参数,而且
$this->$_nom这种是「变量变量」的写法,完全不是你想要的——你要访问的是类的属性_nom,直接写$this->_nom就对了。 - 语法不完整:最后一行的
retu...明显没写完,应该是return。
修正后的完整代码
<?php header("Content-type: text/html; charset=ISO-8859-1"); class Personne { protected $_nom; protected $_prenom; protected $_dateNaissance; protected $_salaire; // 所有方法都要放在类的大括号内部 function getNom(){ return $this->_nom; } function getPrenom(){ return $this->_prenom; } function getDateNaissance(){ return $this->_dateNaissance; } function getSalaire(){ return $this->_salaire; } }
额外小技巧
如果你不想写这么多个getter方法,可以用PHP的__get()魔术方法统一处理属性获取,代码会更简洁:
class Personne { protected $_nom; protected $_prenom; protected $_dateNaissance; protected $_salaire; // 当访问外部不可直接访问的属性时,自动触发这个魔术方法 public function __get($name) { $property = "_" . $name; if (property_exists($this, $property)) { return $this->$property; } throw new Exception("属性 {$name} 不存在哦"); } } // 使用示例(注意protected属性不能直接外部赋值,还需要配合setter或__set()魔术方法) $perso = new Personne(); echo $perso->nom; // 会自动调用__get("nom"),返回_nom的值
内容的提问来源于stack exchange,提问作者Zebra
相关产品推荐
相关产品推荐

