PHP解析错误:语法错误,意外':',期待';'要么 '{'

问题描述 投票:5回答:1

我正在尝试使用php7。我已经安装了https://github.com/rlerdorf/php7dev并通过phpstorm连接。我正在尝试使用这样的新功能:

<?php
namespace Kata;

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

然后我尝试像这样测试它:

<?php
namespace Kata;

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

我用phpunit启动,不幸的是我有

PHP解析错误:语法错误,意外':',期待';'要么 '{'

可能我没有正确安装php7但是当我的php -v似乎没问题

PHP 7.0.0-dev(cli)(内部版本:2015年5月25日16:34:33)(DEBUG)版权所有(c)1997-2015 PHP Group Zend Engine v3.0.0-dev,Copyright(c)1998-2015 Zend Zend Technologies的Zend OPcache v7.0.6-dev技术,版权所有(c)1999-2015

UPDATE

问题不在安装/配置php7(我认为),因为当我从cli运行它时,如下所示:

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

输出int(0)并且没有错误。

所以也许问题出在phpunit中?

php phpunit php-7
1个回答
0
投票

从错误中可以清楚地看到执行代码时出现问题。

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

您的情况下的问题很可能来自PHPUnit,因为您有正确的PHP 7设置。如果PHPUnit无法理解你的代码,它将在PHP 7代码的第一部分失败,在你的情况下使用return type declaration在这一行

public function add(string $parameters): int {

当你试图断言时,它将在你的phpunit测试中被触发。如果您对您的声明进行评论,则错误应该消失。

我建议验证您正在使用的PHPUnit的版本,您应该使用版本5或更高版本。 (最好是6 for php 7.0)有关PHPunit版本的更多细节,请查看qazxsw poi。

© www.soinside.com 2019 - 2024. All rights reserved.