1

我是 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->getFullName());

4

2 回答 2

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, on the other hand, means late static binding -- and, here, will point to your boy class ; which is the one you want to instanciate.
于 2011-04-25T19:31:51.610 回答
0

PHP 的错误报告通常非常好。只需阅读错误。问题在这里:

public static function create($sFirstName,$sLastName){
    return new self($sFirstName,$sLastName);
};

删除训练分号。

public static function create($sFirstName,$sLastName){
    return new self($sFirstName,$sLastName);
}
于 2011-04-25T19:29:45.013 回答