我是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());
有人有什么想法吗?$ girl = girl::create("Jane", "Doe");打印($ oGirl -> getFullName ());
首先要去掉方法定义后面的分号:
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
类;这是你想实例化的对象。
PHP的错误报告通常很好。读一下错误。问题在这里:
public static function create($sFirstName,$sLastName){
return new self($sFirstName,$sLastName);
};
去掉训练分号。
public static function create($sFirstName,$sLastName){
return new self($sFirstName,$sLastName);
}