Introduction to type constraints in PHP _ php instances

Source: Internet
Author: User
Tags spl
This article mainly introduces the type constraints in PHP. PHP class methods and functions can implement type constraints, but the parameters can only specify four types: Class, array, interface, and callable, the parameter can be NULL by default, and PHP cannot constrain scalar type or other types. if you need it, refer to PHP class methods and functions to implement type constraints, however, the parameter can only specify four types: Class, array, interface, and callable. the default value of the parameter can be NULL. PHP cannot restrict the scalar type or other types.

Example:

The code is as follows:


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

// If the parameter of a function call is different from the defined parameter type, a fatal error 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 are constraints on scalar types?

The PECL Extension Library provides the 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 result:
Value not an integer
94
*/

SPL Types reduces flexibility and performance, so you can think twice in your project.

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.