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

不言
Release: 2023-04-03 17:42:02
Original
2513 people have browsed it

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:

<?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.

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

<?php
// 如下面的类
class MyClass {
    public $var = &#39;Hello World&#39;;
}

/**
 * 测试函数
 * 第一个参数必须是 MyClass 类的一个对象
 */
function MyFunction (MyClass $foo) {
    echo $foo->var;
}

// 正确
$myclass = new MyClass;
MyFunction($myclass);
?>
Copy after login

Type constraints allow NULL values:

<?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.

<?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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template