PHP5 type constraint learning Note _php Tutorial

Source: Internet
Author: User
Tags terminates
PHP is a weak type of programming language. In a PHP program, the data type of a variable can change automatically as its value differs, and PHP does not force checks or constraints on the data type of the variable.

We can refer to one of the following simple code examples:

copy code

"!--? php
class Person {

}

$a = 1;//At this time, $a is an integer type (integer)
Var_dump ($a);
$a = 1.0;//At this time, $a is a floating-point type (float)
Var_dump ($a);
$a = ' Codeplayer '; At this point, the $a is a string type (string)
Var_dump ($a),
$a = array (' codeplayer ' = ' http://www.bKjia.c0m ');//At this time, $a the array type (array )
Var_dump ($a);
$a = new person ();//At this time, $a is the Person object type (object)
Var_dump ($a);
$a = mysql_connect (' localhost ', ' username ', ' pas Sword '); At this point, the $a is the resource type (Resource)
Var_dump ($a);
.

The corresponding running effect is as follows:


PHP's weak data type features make PHP simple and flexible to use. However, this is also a sword of Damocles. It is also due to the characteristics of PHP weak data type, when writing PHP program code, developers need to pay attention to the variable data type changes, especially when the variable as a function of the parameters of the transfer, it is more important to pay attention to this point. After all, most of the function parameters are only expected to be of a particular data type. For example, in the following example, the function Sayhi () expects that the type of the parameter to be received is the person object type, but because PHP is not a strongly typed language, it does not force the type of the variable to be checked, so we can pass any type of argument to the function, resulting in a program error or logic exception.

copy code

"!--? php
class Person {
Public $name = ' Codeplayer ';
Public $age = 3;
}

Function Sayhi ($person) {
echo ' hello! My name is $person->name. I ' m $person->age years old. ";
}

$p = ' Zhang San ';
Sayhi ($p);//is not the expected Person object type, notice level error message appears, the program continues to run
Echo ' Suffix ';//will still output this text message
?

Starting with PHP 5, we can use the new type constraint mechanism to type constraints on some of the data types of function parameters. Also in the example above, we can request that the arguments passed in when writing the Sayhi () function must be of the person object type, otherwise a fatal error (Fatal error) is thrown and the current page script is terminated. To use PHP's type constraint mechanism is very simple, we just need to add the specified type name before the parameter variable declared by the function. When we call this function, PHP forces the check to see if the function's arguments are of the specified type and throws a fatal error if it is not the specified type.

copy code

"!--? php
class Person {
Public $name = ' Codeplayer ';
Public $age = 3;
}

Function sayhi (person $person) {
echo ' hello! My name is $person->name. I ' m $person->age years old. ";
}

$person = ' Zhang San ';
Sayhi ($person);//Not expected person object type, throws fatal error fatal error, program terminates run
Echo ' Suffix '; Does not output this text message, the program terminates running
?

It is worth noting that in PHP 5, only the object, interface, array, callable type parameter variables can use type constraints (the array type is supported from the PHP 5.1 version, the callable type is supported from the beginning of PHP 5.4).
Note: If a parameter variable that uses a type constraint does not declare its default value to be NULL, you cannot pass a null value to the corresponding parameter variable when the function is called, otherwise the same error will be given.


Type constraints cannot be used with scalar types such as int or string. Traits is not allowed.

Example #1 Type Constraint example

The code is as follows Copy Code

As in the following class
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 definition
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.

code as follows copy code

Two classes of objects
$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 argument 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:

The code is as follows Copy Code

As in the following class
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;
}

That's right
$myclass = new MyClass;
MyFunction ($myclass);
?>
Type constraints allow NULL values:

/* Accept NULL values */
function Test (StdClass $obj = NULL) {

}

Test (NULL);
Test (new StdClass);

?>

http://www.bkjia.com/PHPjc/632617.html www.bkjia.com true http://www.bkjia.com/PHPjc/632617.html techarticle PHP is a weak type of programming language. In a PHP program, the data type of a variable can change automatically as its value differs, and PHP does not force the data type of the variable to be checked ...

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