Home Backend Development PHP Tutorial What are php type constraints? Introduction and usage of php type constraints

What are php type constraints? Introduction and usage of php type constraints

Aug 08, 2018 pm 05:14 PM
php constraint

The so-called type constraint means that when defining a variable, its type must be specified, and the variable can only store data of this type in the future. In this article, I will introduce you to PHP type constraints and usage.

Introduction to php type constraints

PHP is a weakly typed language. Its characteristic is that there is no need to specify a type for a variable, and any type can be stored afterwards. , of course, this is also one of the key points for 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. It must be an object (specify the name of the class in the function prototype);

2. Interface;

3. Array (from PHP 5.1);

4. Callable (from PHP 5.4).

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

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

Note: Before PHP7, type constraints could not be used for scalar types such as int or string. Traits are not allowed either.

Usage of php type constraints:

The following is the official example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

<?php

//如下面的类

class MyClass

{

    /**

     * 测试函数

     * 第一个参数必须为 OtherClass 类的一个对象

     */

    public function test(OtherClass $otherclass) {

        echo $otherclass->var;

    }

 

 

    /**

     * 另一个测试函数

     * 第一个参数必须为数组 

     */

    public function test_array(array $input_array) {

        print_r($input_array);

    }

}

 

    /**

     * 第一个参数必须为递归类型

     */

    public function test_interface(Traversable $iterator) {

        echo get_class($iterator);

    }

     

    /**

     * 第一个参数必须为回调类型

     */

    public function test_callable(callable $callback$data) {

        call_user_func($callback$data);

    }

}

 

// OtherClass 类定义

class OtherClass {

    public $var 'Hello World';

}

?>

Copy after login

Parameters of function calls and defined parameter types In case of inconsistency, a catchable fatal error is thrown.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

<?php

// 两个类的对象

$myclass = new MyClass;

$otherclass = new OtherClass;

 

// 致命错误:第一个参数必须是 OtherClass 类的一个对象

$myclass->test('hello');

 

// 致命错误:第一个参数必须为 OtherClass 类的一个实例

$foo new stdClass;

$myclass->test($foo);

 

// 致命错误:第一个参数不能为 null

$myclass->test(null);

 

// 正确:输出 Hello World 

$myclass->test($otherclass);

 

// 致命错误:第一个参数必须为数组

$myclass->test_array('a string');

 

// 正确:输出数组

$myclass->test_array(array('a''b''c'));

 

// 正确:输出 ArrayObject

$myclass->test_interface(new ArrayObject(array()));

 

// 正确:输出 int(1)

$myclass->test_callable('var_dump', 1);

?>

Copy after login

Type constraints are not only used in member functions of classes, but can also be used in functions:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<?php

// 如下面的类

class MyClass {

    public $var = 'Hello World';

}

 

/**

 * 测试函数

 * 第一个参数必须是 MyClass 类的一个对象

 */

function MyFunction (MyClass $foo) {

    echo $foo->var;

}

 

// 正确

$myclass new MyClass;

MyFunction($myclass);

?>

Copy after login

Type constraints allow NULL values:

1

2

3

4

5

6

7

8

9

10

11

<?php

 

/* 接受 NULL 值 */

function test(stdClass $obj = NULL) {

 

}

 

test(NULL);

test(new stdClass);

 

?>

Copy after login

PHP7

Scalar type declaration (PHP 7)

There are two modes for scalar type declaration: mandatory (default) and strict mode.
The following type parameters can now be used (whether in forced mode or strict mode):

1, string (string),

2, integer (int),

3. Floating point number (float),

4. Boolean value (bool).

They extend other types introduced in PHP5: class names, interfaces, arrays and callback types.

1

2

3

4

5

6

7

8

<?php

// 强制模式

function sumOfInts(int ...$ints)

{

     return array_sum($ints);

}

  

var_dump(sumOfInts(2, '3', 4.1));

Copy after login

The above example will output: int(9)

To use strict mode, a declare declaration directive must be placed at the top of the file. This means that scalars are strictly declared configurable on a file basis. This directive not only affects the type declaration of parameters, but also affects the return value declaration of functions.

Recommended related articles:

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

Sharing of code ideas for type constraints in PHP

How to use type constraints to limit php function types

The above is the detailed content of What are php type constraints? Introduction and usage of php type constraints. For more information, please follow other related articles on the PHP Chinese website!

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

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

CakePHP Project Configuration

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

CakePHP Date and Time

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

CakePHP File upload

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

CakePHP Routing

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

Discuss CakePHP

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

How To Set Up Visual Studio Code (VS Code) for PHP Development

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP Quick Guide

See all articles