PHP 7: use both strict and non-strict type hinting?

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

So PHP 7 has scalar type hinting now (w00t!), and you can have the type hints be strict or non-strict depending on a setting in PHP. Laracasts set this using define, IIRC.

Is there a way to have strict type hinting on scalars in one file (like a math library) while at the same time using non-strict elsewhere WITHOUT just arbitrarily changing settings in your code?

I'd like to avoid introducing bugs by not fidgeting with the language settings, but I like this idea.

回答1:

Indeed, you can mix and match to your heart's content, in fact the feature was specifically designed to work that way.

declare(strict_types=1); isn't a language setting or configuration option, it's a special per-file declaration, a bit like namespace ...;. It only applies to the files you use it in, it won't affect other files.

So, for example:

<?php // math.php  declare(strict_types=1); // strict typing  function add(float $a, float $b): float {     return $a + $b; }  // this file uses strict typing, so this won't work: add("1", "2");

<?php // some_other_file.php  // note the absence of a strict typing declaration  require_once "math.php";  // this file uses weak typing, so this _does_ work: add("1", "2");

Return typing works the same way. declare(strict_types=1); applies to function calls (NOT declarations) and return statements within a file. If you don't have a declare(strict_types=1); statement, the file uses "weak typing" mode.



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