Home  >  Article  >  Backend Development  >  Introduction to type constraints in PHP_PHP tutorial

Introduction to type constraints in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:54:12808browse

Introduction to type constraints in PHP

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. The parameters can be NULL by default. PHP cannot constrain scalar types or other types. Friends in need can refer to the following

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.

Example as follows:

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.

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 results:

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/998360.htmlTechArticleIntroduction to type constraints in PHP This article mainly introduces the introduction to type constraints in PHP, PHP class methods and Type constraints can be implemented in functions, but parameters can only specify classes, arrays, interfaces, cal...
Statement:
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