PHP Parse error: syntax error, unexpected ':', expecting ';' or '{'

戏子无情 提交于 2021-01-27 06:00:35

问题


I'm try playing with php7. I have installed https://github.com/rlerdorf/php7dev and connected through phpstorm. I'm trying use new feature like this:

<?php
namespace Kata;

class StringCalculator
{
    public function add(string $parameters): int {
        return 0;
    }
}

then I try to test it like this:

<?php
namespace Kata;

class StringCalculatorTest extends \PHPUnit_Framework_TestCase
{
    public function testAddEmptyString()
    {
        $calc = new StringCalculator();
        $this->assertSame(0, $calc->add(''));
    }
}

and I launch with phpunit, unfortunately I have

PHP Parse error: syntax error, unexpected ':', expecting ';' or '{'

Probably I haven't installed php7 properly but it seems to be ok when I php -v

PHP 7.0.0-dev (cli) (built: May 25 2015 16:34:33) (DEBUG) Copyright (c) 1997-2015 The PHP Group Zend Engine v3.0.0-dev, Copyright (c) 1998-2015 Zend Technologies with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies

UPDATE

Problem is not in installation/configuration php7 (I think), because when I run it from cli like this:

<?php
    $calc = new Kata\StringCalculator();
    var_dump($calc->add(''));

outputs int(0) and no error.

So maybe the problem is in phpunit?


回答1:


From the error it is clear that there's a problem executing your code.

PHP Parse error: syntax error, unexpected ':', expecting ';' or '{'

The problem in your case is most likely coming from PHPUnit since you have a correct php 7 setup. If PHPUnit fails to understand your code it's gonna fail in the first bit of PHP 7 code which in your case using a return type declaration in this line

public function add(string $parameters): int {

and it's gonna be triggered in your phpunit test when you try to assert. If you comment your assersion the error should disappear.

I suggest verifiying the version of PHPUnit you are using, you should use version 5 or higher. (preferably 6 for php 7.0) For more details about PHPunit versions, checkout this link.



来源:https://stackoverflow.com/questions/32914266/php-parse-error-syntax-error-unexpected-expecting-or

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!