我是OOP的新手,我一直在研究这个例子,但我似乎无法摆脱这个错误
Parse error: syntax error, unexpected ';', expecting T_FUNCTION in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\...\php_late_static_bindings.php on line 16
我试图执行以下代码:
abstract class father {
protected $lastname="";
protected $gender="";
function __construct($sLastName){
$this->lastname = $sLastName;
}
abstract function getFullName();
public static function create($sFirstName,$sLastName){
return new self($sFirstName,$sLastName);
};
}
class boy extends father{
protected $firstname="";
function __construct($sFirstName,$sLastName){
parent::__construct($sLastName);
$this->firstname = $sFirstName;
}
function getFullName(){
return("Mr. ".$this->firstname." ".$this->lastname."<br />");
}
}
class girl extends father{
protected $firstname="";
function __construct($sFirstName,$sLastName){
parent::__construct($sLastName);
$this->firstname = $sFirstName;
}
function getFullName(){
return("Ms. ".$this->firstname." ".$this->lastname."<br />");
}
}
$oBoy = boy::create("John", "Doe");
print($oBoy->getFullName());
有没有人有任何想法? $ oGirl = girl :: create(“Jane”,“Doe”); 打印($ oGirl-&GT; getFullName());
答案 0 :(得分:1)
首先必须删除方法定义后的分号:
public static function create($sFirstName,$sLastName){
return new self($sFirstName,$sLastName);
} // there was a semi-colon, here
然后,您可能希望使用static
,而不是self
,此处:
public static function create($sFirstName,$sLastName){
return new static($sFirstName,$sLastName);
}
说明:
self
指向编写它的类 - 这里是father
类,它是抽象的,不能实例化。static
表示后期静态绑定 - 并且,此处将指向您的boy
类;这是你想要实现的那个。答案 1 :(得分:0)
PHP的错误报告通常非常好。只需阅读错误。问题出在这里:
public static function create($sFirstName,$sLastName){
return new self($sFirstName,$sLastName);
};
删除训练分号。
public static function create($sFirstName,$sLastName){
return new self($sFirstName,$sLastName);
}