What is the PHP type constraint? Introduction and usage of PHP type constraints

Source: Internet
Author: User
Tags scalar
The so-called type constraint is when you define a variable, you must specify its type, and later the variable can only store that type of data. In this article, I will introduce you to PHP type constraints and usage.

Introduction to PHP type constraints

PHP is a weakly typed language, which is characterized by the need not to specify a type for a variable, but also to store any type thereafter, which is one of the key points of rapid development using PHP. But since PHP5, we can use type constraints in function (method) parameters.

The parameters of the function can be specified in the following range:

1. Must be an object (the name of the class is specified inside the function prototype);

2, interface;

3, Array (PHP 5.1);

4, callable (PHP 5.4).

5. If you use NULL as the default value for the parameter, you can still use NULL as the argument when calling the function.

6. If a class or interface specifies a type constraint, all of its subclasses or implementations also do so.

Note : Before PHP7, type constraints cannot be used with scalar types such as int or string. Traits is not allowed.

Usage of PHP type constraints:

Here are the official examples:

<?php//class myclass{    /**     * Test function     * The first parameter must be an object of the Otherclass class * * Public    function test ( Otherclass $otherclass) {        echo $otherclass->var;    }    /**     * Another test function     * The first parameter must be an array */public    function test_array (array $input _array) {        Print_r ($input _array);}    }    /**     * The first parameter must be a recursive type     *    /Public Function test_interface (traversable $iterator) {        echo get_class ($ iterator);    }        /**     * The first parameter must be a callback type */public    function test_callable (callable $callback, $data) {        Call_user_func ( $callback, $data);}    } Otherclass class Otherclass {public    $var = ' Hello world ';}? >

A catch fatal error is thrown when the parameters of a function call are inconsistent with the defined parameter type.

<?php//object of two classes $myclass = new MyClass; $otherclass = new otherclass;//fatal error: The first argument must be an object of the Otherclass class $myclass->test (' hello ');//Fatal error: The first parameter must be an instance of the Otherclass class $foo = new StdClass; $myclass->test ($foo);//Fatal error: The first parameter cannot be null$myclass- >test (null);//correct: Output Hello world $myclass->test ($otherclass);//Fatal error: The first parameter must be an array $myclass->test_array (' A String ');//correct: Output array $myclass->test_array (Array (' A ', ' B ', ' C '));//correct: Output Arrayobject$myclass->test_interface ( New Arrayobject (Array ()));//correct: Output int (1) $myclass->test_callable (' Var_dump ', 1);? >

Type constraints are not only used in the member functions of a class, but also in functions:

<?php//class MyClass {public    $var = ' Hello world ';} /** * Test function * The first parameter must be an object of the MyClass class */function MyFunction (MyClass $foo) {    echo $foo->var;} Correct $myclass = new MyClass; MyFunction ($myclass);? >

Type constraints allow NULL values:

<?php/* accepts a NULL value */function Test (stdClass $obj = null) {}test (null); Test (new StdClass);? >

PHP7

Scalar type declaration (PHP 7)

Scalar type declarations have two modes: mandatory (default) and strict mode.
You can now use the following type parameters, whether in forced or strict mode:

1, String,

2, Integer (int),

3, floating point (float),

4, Boolean value (BOOL).

They augment the other types introduced in PHP5: Class name, interface, array, and callback type.

<?php//Force mode function sumofints (int ... $ints) {     return array_sum ($ints);} var_dump (Sumofints (2, ' 3 ', 4.1));

The results of the above example output: Int (9)

To use strict mode, a declare declaration directive must be placed at the top of the file. This means that the scalar is strictly declared to be file-based. This directive affects not only the type declaration of the parameter, but also the return value declaration of the function.

Related Article

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.