Home > Article > Backend Development > Code sharing of ideas for type constraints in php
As we all know, in strongly typed languages, type constraints are grammatical requirements, that is: when defining a variable, its type must be specified, and in the future the variable can only store data of this type, HP class methods and functions Type constraints can be implemented in , but parameters can only specify four types: class, array, interface, and callable. Parameters can default to NULL. PHP cannot constrain scalar types or other types.
The first step is to download the type constraint class library in PHP that we need to use in this course: http://www.php.cn/xiazai/leiku/629
Step 2: After the download is completed, find the php class file we need, unzip it to our local directory, and create a new php file!
The third step, after completion, we need to call this class in the new php file and instantiate the class:
<?php include_once "test.php";//引入类文件 $test = new Test(); //函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误。 $test->test_array(array(1));echo "<br>"; $test->test_class(new Test1());echo "<br>"; $test->test_callable('print_r', 1);echo "<br>"; $test->test_interface(new ArrayObject(array()));echo "<br>"; $test->test_class_with_null(); ?>
Run this file and get the result as shown below:
The above is the detailed content of Code sharing of ideas for type constraints in php. For more information, please follow other related articles on the PHP Chinese website!