Introduction to type constraints in php

怪我咯
Release: 2023-03-13 22:32:02
Original
1279 people have browsed it

PHP is a weak type. Its characteristic is that there is no need to specify a type for the variable, and any type can be stored afterwards. However, in the new syntax of php, in some specific occasions, for some Specific types can also be grammatically constrained.

Specific occasions: formal parameter variables of functions (methods)

Specific types: object type (class name), interface type (interface name), array Type (array), function type (callable)

This article mainly introduces Type constraints in PHPIntroduction, type constraints can be implemented in PHP class methods and functions, However, parameters can only specify four types: class, array, interface, and callable. Parameters can default to NULL. PHP cannot constrain scalar types or other types. Friends in need can refer to the following

The following example:

test_array(array(1));
$test->test_class(new Test1());
$test->test_callable('print_r', 1);
$test->test_interface(new ArrayObject(array()));
$test->test_class_with_null();
Copy after login

So how to constrain the scalar type?

The PECL extension library provides SPL Types extension to implement interger, float, bool, enum, and string type constraints.

The code is as follows:

$int  = new  SplInt ( 94 );
 
try {
     $int  =  'Try to cast a string value for fun' ;
} catch ( UnexpectedValueException $uve ) {
    echo  $uve -> getMessage () .  PHP_EOL ;
}
 
echo  $int  .  PHP_EOL ;
/*
运行结果:
Value not an integer
94
*/
Copy after login

PS: SPL Types will reduce certain flexibility and performance, so think twice in actual projects.

The above is the detailed content of Introduction to 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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!