Home  >  Article  >  Backend Development  >  PHP关于官方文档的一些问题

PHP关于官方文档的一些问题

WBOY
WBOYOriginal
2016-06-06 20:24:581328browse

以下问题运行在php5.5
小弟刚学PHP没几天
求大神指教

1.官方文档给出的这个实例中
declare(strict_type=1);
这个严格声明为何显示为一个不支持的声明...
然后把严格声明去掉后,下面两个int型的sum(1,2)也无法传入函数= =

<code class="php"><?php declare(strict_types=1);

function sum(int $a, int $b) {
    return $a + $b;
}

var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
?></code>

2.这个实例中,function后面的: float是啥子意思?
是不是传进的数return出来的全变成浮点型?
然后依然执行错误

<code class="php"><?php function sum($a, $b): float {
    return $a + $b;
}

// Note that a float will be returned.
var_dump(sum(1, 2));
?> </code>

回复内容:

以下问题运行在php5.5
小弟刚学PHP没几天
求大神指教

1.官方文档给出的这个实例中
declare(strict_type=1);
这个严格声明为何显示为一个不支持的声明...
然后把严格声明去掉后,下面两个int型的sum(1,2)也无法传入函数= =

<code class="php"><?php declare(strict_types=1);

function sum(int $a, int $b) {
    return $a + $b;
}

var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
?></code>

2.这个实例中,function后面的: float是啥子意思?
是不是传进的数return出来的全变成浮点型?
然后依然执行错误

<code class="php"><?php function sum($a, $b): float {
    return $a + $b;
}

// Note that a float will be returned.
var_dump(sum(1, 2));
?> </code>

function后面的: float指的是该函数返回值的类型。
强类型strict_type是从PHP7开始才引入的东西,默认是不开启的,以后也不会默认开启,是一个很有争议性的特性。PHP之父rasmus,Zend公司创始人andi,PHP7性能方面的核心开发者dmitry和鸟哥laruence都投了反对票:
https://wiki.php.net/rfc/scalar_type_hints_v5

你写的是php7的代码,declare也好,类型指定也好,都是php7的特性
因为php7是个较大改动的新版本,所以这些特性php5.5并不支持

鉴于当下的环境过渡到php7还需要一段时间,你可以先看一下php5.5或php5.6的文档上手,然后再去看php7的新特性

这是PHP 5.6到PHP 7的迁移指南 https://github.com/vimac/Migrating-from-PHP5.6.x-to-PHP7.0.x,你可以当做是了解PHP 7新特性的地方

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn