PHP7中標量類型declare的用法詳解

來源:互聯網
上載者:User
這篇文章主要介紹了PHP7標量類型declare用法,結合執行個體形式分析了PHP7中標量類型declare的功能、特性與相關提示,需要的朋友可以參考下

本文執行個體講述了PHP7標量類型declare用法。分享給大家供大家參考,具體如下:

php7為了提高執行效率,在函數方法中增加了標量類型(布爾、浮點、整型、字元)的申明特性,節省了對資料類型的檢測。

php7 仍然支援弱類型檢測,即仍然可以使用原來的方式聲明形參。

標量聲明有兩種特性:

強制模式(預設):體現在類型轉換上

strict 模式

模式聲明:declare(strict_types=1);

預設情況值為0,值為1代表為嚴格校正的模式

可以使用的型別參數:

int-float-bool-string-interfaces-array-callable

作用於形參與傳回值類型說明,可選

形參

//強制模式<?php/** * Created by PhpStorm. * User: bee * Date: 2016/4/22 * Time: 10:17 */// php7之前申明方式function type_weak(... $int){  return array_sum($int);}// 強制模式 php7聲明方式//強制模式下會將所有實參轉換為整型function sum(int ... $ints){  //array_sum() 將數組中的所有值的和以整數或浮點數的結果返回。  print_r($ints);  echo "<br>";  return array_sum($ints);}echo type_weak(2, '3',0.11);echo "<hr>";echo sum(2, '3',0.11);

運行如下:

//將模式申明為strict 模式<?php/** * Created by PhpStorm. * User: bee * Date: 2016/4/22 * Time: 10:17 */ //declare 必須在檔案首部declare(strict_types=1);// 強制模式(預設)function type_weak(... $int){  return array_sum($int);}// 強制模式function sum(int ... $ints){  //array_sum() 將數組中的所有值的和以整數或浮點數的結果返回。  print_r($ints);  echo "<br>";  return array_sum($ints);}echo type_weak(2, '3',0.11);echo "<hr>";//實參存在字串與浮點型,報錯echo sum(2, '3',0.11);

運行如下:

傳回值

<?php/** * Created by PhpStorm. * User: bee * Date: 2016/4/22 * Time: 10:17 */declare(strict_types=0);// 強制模式(預設)function type_weak(... $int) :int{  return array_sum($int);}// 強制模式function sum(int ... $ints) :int{  //array_sum() 將數組中的所有值的和以整數或浮點數的結果返回。  print_r($ints);  echo "<br>";  //strict 模式下報錯  return array_sum($ints)+0.6;}echo type_weak(2, '3',0.11);echo "<hr>";echo sum(2, '3',0.11);

運行如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.