Home > Backend Development > PHP Tutorial > Introduction to type constraints in PHP, introduction to PHP type constraints_PHP tutorial

Introduction to type constraints in PHP, introduction to PHP type constraints_PHP tutorial

WBOY
Release: 2016-07-13 09:54:30
Original
953 people have browsed it

Introduction to type constraints in PHP, introduction to PHP type constraints

Type constraints can be implemented in PHP class methods and functions, but parameters can only specify classes, arrays, interfaces, and callables Four types, parameters can default to NULL, PHP cannot constrain scalar types or other types.

Example below:
Copy code The code is as follows:

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();

//When the parameters of the function call are inconsistent with the defined parameter types, a catchable fatal error will be thrown.

$test->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();

So how to constrain scalar types?

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

Copy code 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 ;
/*
Running result:
Value not an integer
94
*/

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/997904.htmlTechArticleIntroduction to type constraints in PHP, introduction to PHP type constraints 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 be silent...
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