开发者

php late static binding revieve error expecting T_FUNCTION

I am new to OOP and I have been working on this example but I cannot seem to get rid of this error

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

I was attempting to execute the follow code:

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 />"开发者_JAVA技巧);
    }
}

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());

Does anyone have any ideas? $oGirl = girl::create("Jane", "Doe"); print($oGirl->getFullName());


You first have to remove the semi-colon that's after your method definition :

public static function create($sFirstName,$sLastName){
    return new self($sFirstName,$sLastName);
} // there was a semi-colon, here


Then, you probably want to use static, and not self, here :

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

Explanation :

  • self points to the class in which it is written -- here, the father class, which is abstract, and cannot be instanciated.
  • 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.


PHP's error reporting is usually pretty good. Just read the error. The problem is here:

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

Remove the training semicolon.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜