


What are php type constraints? Introduction and usage of php type constraints
The so-called type constraint means that when defining a variable, its type must be specified, and the variable can only store data of this type in the future. In this article, I will introduce you to PHP type constraints and usage.
Introduction to php type constraints
PHP is a weakly typed language. Its characteristic is that there is no need to specify a type for a variable, and any type can be stored afterwards. , of course, this is also one of the key points for rapid development using PHP. But since PHP5, we can use type constraints in function (method) parameters.
The parameters of the function can be specified in the following range:
1. It must be an object (specify the name of the class in the function prototype);
2. Interface;
3. Array (from PHP 5.1);
4. Callable (from PHP 5.4).
5. If you use NULL as the default value of the parameter, you can still use NULL as the actual parameter when calling the function.
6. If a class or interface specifies type constraints, so do all its subclasses or implementations.
Note: Before PHP7, type constraints could not be used for scalar types such as int or string. Traits are not allowed either.
Usage of php type constraints:
The following is the official example:
<?php //如下面的类 class MyClass { /** * 测试函数 * 第一个参数必须为 OtherClass 类的一个对象 */ public function test(OtherClass $otherclass) { echo $otherclass->var; } /** * 另一个测试函数 * 第一个参数必须为数组 */ public function test_array(array $input_array) { print_r($input_array); } } /** * 第一个参数必须为递归类型 */ public function test_interface(Traversable $iterator) { echo get_class($iterator); } /** * 第一个参数必须为回调类型 */ public function test_callable(callable $callback, $data) { call_user_func($callback, $data); } } // OtherClass 类定义 class OtherClass { public $var = 'Hello World'; } ?>
Parameters of function calls and defined parameter types In case of inconsistency, a catchable fatal error is thrown.
<?php // 两个类的对象 $myclass = new MyClass; $otherclass = new OtherClass; // 致命错误:第一个参数必须是 OtherClass 类的一个对象 $myclass->test('hello'); // 致命错误:第一个参数必须为 OtherClass 类的一个实例 $foo = new stdClass; $myclass->test($foo); // 致命错误:第一个参数不能为 null $myclass->test(null); // 正确:输出 Hello World $myclass->test($otherclass); // 致命错误:第一个参数必须为数组 $myclass->test_array('a string'); // 正确:输出数组 $myclass->test_array(array('a', 'b', 'c')); // 正确:输出 ArrayObject $myclass->test_interface(new ArrayObject(array())); // 正确:输出 int(1) $myclass->test_callable('var_dump', 1); ?>
Type constraints are not only used in member functions of classes, but can also be used in functions:
<?php // 如下面的类 class MyClass { public $var = 'Hello World'; } /** * 测试函数 * 第一个参数必须是 MyClass 类的一个对象 */ function MyFunction (MyClass $foo) { echo $foo->var; } // 正确 $myclass = new MyClass; MyFunction($myclass); ?>
Type constraints allow NULL values:
<?php /* 接受 NULL 值 */ function test(stdClass $obj = NULL) { } test(NULL); test(new stdClass); ?>
PHP7
Scalar type declaration (PHP 7)
There are two modes for scalar type declaration: mandatory (default) and strict mode.
The following type parameters can now be used (whether in forced mode or strict mode):
1, string (string),
2, integer (int),
3. Floating point number (float),
4. Boolean value (bool).
They extend other types introduced in PHP5: class names, interfaces, arrays and callback types.
<?php // 强制模式 function sumOfInts(int ...$ints) { return array_sum($ints); } var_dump(sumOfInts(2, '3', 4.1));
The above example will output: int(9)
To use strict mode, a declare declaration directive must be placed at the top of the file. This means that scalars are strictly declared configurable on a file basis. This directive not only affects the type declaration of parameters, but also affects the return value declaration of functions.
Recommended related articles:
Introduction to type constraints in PHP, introduction to PHP type constraints
Sharing of code ideas for type constraints in PHPHow to use type constraints to limit php function types
The above is the detailed content of What are php type constraints? Introduction and usage of php type constraints. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download
The most popular open source editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
