Php5 type constraint learning NOTE _ PHP Tutorial

Source: Internet
Author: User
Php5 type constraints learning notes. Php is a weak programming language. In a php program, the data type of a variable can automatically change with its value, php does not forcibly check the data types of variables. php is a weak programming language. In a php program, the data type of a variable can automatically change with its value. php does not forcibly check or constrain the data type of the variable.

We can refer to the following simple code example:

The code is as follows:

Class Person {

}

$ A = 1; // $ a is an Integer)
Var_dump ($ );
$ A = 1.0; // $ a is of the floating point type (Float)
Var_dump ($ );
$ A = 'codeplayer '; // at this time, $ a is of the String type (String)
Var_dump ($ );
$ A = array ('codeplayer '=> 'http: // www. bKjia. c0m'); // at this time, $ a is an Array type (array)
Var_dump ($ );
$ A = new Person (); // at this time, $ a is of the Person Object type (Object)
Var_dump ($ );
$ A = mysql_connect ('localhost', 'username', 'password'); // $ a indicates the Resource type)
Var_dump ($ );
?>

Shows the corresponding running effect:


The weak data type of php makes php easy to use and flexible. However, this is also a sword of damaklis. It is precisely because of the weak data types in php that when writing php code, developers need to pay more attention to the changes in variable data types, especially when variables are passed as function parameters, pay more attention to this. After all, most function parameters only expect a specific data type. For example, in the following example, the parameter type that the function sayHi () expects to receive is the Person object type. However, because php is not a strong language, it does not forcibly check the variable type, therefore, we can pass any type of parameters to the function, resulting in program errors or logical exceptions.

The code is as follows:

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); // if it is not the expected Person object type, a Notice-level error message will appear and the program continues to run.
Echo 'suffix '; // The text is still output.
?>

From php 5, we can use the newly added type constraint mechanism to type some data types of function parameters. The code above is also used as an example. when writing the sayHi () function, the parameter must be of the Person object type. Otherwise, a Fatal Error is thrown ), and terminate the running of the script on the current page. To use the php type constraint mechanism, you only need to add the specified type name before the parameter variables declared by the function. When we call this function, php will forcibly check whether the function parameter is of the specified type. if it is not of the specified type, a fatal error is thrown.

The code is as follows:

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); // It is not the expected Person object type, causing a Fatal Error and program termination
Echo 'suffix '; // does not output the text information and the program stops running.
?>

It is worth noting that in php 5, only parameter variables of the object, interface, array, and callable types can use type constraints (the array type is supported since php 5.1, callable type is supported from php 5.4 ).
Note: If the default value of a parameter variable with type constraints is not declared as null, you cannot pass a null value to the corresponding parameter variable when calling this function. Otherwise, an error is returned.


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

Example #1 type constraints

The code is as follows:

// The following class
Class MyClass
{
/**
* Test functions
* 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 of the recursive type.
*/
Public function test_interface (Traversable $ iterator ){
Echo get_class ($ iterator );
}

/**
* The first parameter must be of the callback type.
*/
Public function test_callable (callable $ callback, $ data ){
Call_user_func ($ callback, $ data );
}
}

// OtherClass class definition
Class OtherClass {
Public $ var = 'Hello World ';
}
?>

When a function call parameter is different from the defined parameter type, a fatal error is thrown.

The code is as follows:

// Two class objects
$ Myclass = new MyClass;
$ Otherclass = new OtherClass;

// Fatal error: The first parameter 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 member functions of the class, but also in functions:

The code is as follows:

// The following class
Class MyClass {
Public $ var = 'Hello World ';
}

/**
* Test functions
* 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:

/* Accept NULL values */
Function test (stdClass $ obj = NULL ){

}

Test (NULL );
Test (new stdClass );

?>

Bytes. In a php program, the data type of a variable can automatically change with the value. php does not forcibly check the data type of the variable...

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.