Home > Backend Development > PHP Tutorial > Type constraints in PHP

Type constraints in PHP

*文
Release: 2023-03-18 15:34:01
Original
1669 people have browsed it

This article mainly introduces the introduction of type constraints in PHP. Type constraints can be implemented in PHP class methods and functions, but parameters can only specify four types: class, array, interface, and callable. Parameters can default to NULL, and PHP does not Cannot constrain scalar types or other types. Hope this article is helpful to everyone.

Type constraints can be implemented in PHP class methods and functions, 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 following example:

<?php
 
class Test
{
    public function test_array(array $arr)
    {
        print_r($arr);
    }
 
    public function test_class(Test1 $test1 = null)
    {
        print_r($test1);
    }
 
    public function test_callable(callable $callback, $data)
    {
        call_user_func($callback, $data);
    }
 
    public function test_interface(Traversable $iterator)
    {
        print_r(get_class($iterator));
    }
 
    public function test_class_with_null(Test1 $test1 = NULL)
    {
 
    }
}
 
class Test1{}
 
$test = new Test();
 
//函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误。
 
$test->test_array(array(1));
$test->test_class(new Test1());
$test->test_callable(&#39;print_r&#39;, 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.

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

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

Related recommendations:

PHP data types and judgment variable types

PHP function attention

Some neglected PHP functions (organized)

The above is the detailed content of 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