Home > Article > Backend Development > The meaning of php7 type constraints
The meaning of php7 type constraints
beforePHP7 , functions and class methods do not need to declare variable types, and any data can be passed and returned, causing almost most calling operations to determine whether the returned data type is qualified.
To solve this problem, PHP7 introduced type declarations.
There are currently two types of variables that can be declared: formal parameters and return values.
Supported types include integer, floating point, string, and Boolean.
The following code:
<?php function study(int $get) { return $get; } var_dump(study('ddd'));
In order to save the length of the code, I will not write OOP, just use the function as an example.
This function specifies that the parameter type is int, and the 'ddd' string is passed in when it is called, so a Fatal error will occur when running this code.
In some cases, PHP is always not so serious, as follows:
<?php function study(bool $get) { return $get; } var_dump(study('ddd'));
The specified parameter type is bool, but the incoming string is converted into true, The output result after running is: bool(true)
If you want to force the constraint type, you can add a declare statement at the head of the file:
<?php declare(strict_types = 1); function study(bool $get) { return $get; } var_dump(study('ddd'));
At this time, it will also A fatal error occurs because the specified parameter type is bool but the passed parameter type is string. Only changing 'ddd' to true and false will work, even if it is 1 or 0.
Next, let’s introduce the return type declaration:
<?php declare(strict_types = 1); function study(bool $get) : int { return (int)$get; } var_dump(study(true));
Add a colon and type after the parentheses of the formal parameter to specify the type of method return value and what type of return is specified. That's what type.
It is also affected by declare.
If there is no type mandatory constraint, then PHP will convert the returned data into the specified type of data and then return it. Currently, only string cannot be forced to int. An error will be reported.
If mandatory constraints are specified, PHP will not perform type conversion, but will compare. If the types are different, an error will be reported.
Also, the return value type can also specify the object name, then the instance of the specified object must be returned, such as:
<?php class person { private function __construct($name) { $this->name = $name; } static function instance(string $name) : person { return new self($name); } } person::instance('zhangsan');
This is One of the new features of PHP7: type declaration.
The above is the detailed content of The meaning of php7 type constraints. For more information, please follow other related articles on the PHP Chinese website!