Code sharing of ideas for type constraints in php

黄舟
Release: 2023-03-15 11:38:02
Original
1671 people have browsed it

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(&#39;print_r&#39;, 1);echo "<br>";
$test->test_interface(new ArrayObject(array()));echo "<br>";
$test->test_class_with_null();
?>
Copy after login

Run this file and get the result as shown below:

Code sharing of ideas for type constraints in php

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template