Introduction to type Constraints in PHP

Source: Internet
Author: User
Tags arrays spl php class php and scalar

This article mainly introduces the type constraint in PHP, PHP class methods and functions can be implemented type constraints, but the parameters can only specify classes, arrays, interfaces, callable four types, parameters can default to null,php and can not constrain the scalar type or other types, the need for friends can refer to the

Type constraints can be implemented in PHP's class methods and functions, but parameters can only specify classes, arrays, interfaces, callable four types, and parameters can default to null,php and cannot constrain scalar types or other types.

The following example:

The code is as follows:

  

Class Test

{

Public function Test_array (array $arr)

{

Print_r ($arr);

}

Public Function Test_class (Test1 $test 1 = null)

{

Print_r ($test 1);

}

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 $test 1 = null)

{

}

}

Class test1{}

$test = new test ();

When a function calls an argument that is inconsistent with a defined parameter type, a fatal error that can be caught is 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 do you constrain scalar types?

The SPL types extension implements Interger, float, bool, enum, String type constraints in the PECL extension library.

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;

/*

Run Result:

Value not an integer

94

*/

SPL types will reduce a certain amount of flexibility and performance in the actual project to reconsider.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.