Php5 type constraint learning Notes

Source: Internet
Author: User
Php is a weak programming language. in php programs, the data types of variables can automatically change with their values, php does not forcibly check or constrain the data type of the variable.

Php is a weak programming language. in php programs, the data types of variables can automatically change with their values, php does not forcibly check or constrain the data type of the variable.

We can refer to the following simple code example:

  1. Class Person {
  2. }
  3. $ A = 1; // $ a is an Integer)
  4. Var_dump ($ );
  5. $ A = 1.0; // $ a is of the floating point type (Float)
  6. Var_dump ($ );
  7. $ A = 'codeplayer '; // at this time, $ a is of the String type (String)
  8. Var_dump ($ );
  9. $ A = array ('codeplayer '=> 'http: // www.111cn.net'); // at this time, $ a is an Array type (array)
  10. Var_dump ($ );
  11. $ A = new Person (); // at this time, $ a is of the Person Object type (Object)
  12. Var_dump ($ );
  13. $ A = mysql_connect ('localhost', 'username', 'password'); // $ a indicates the Resource type)
  14. Var_dump ($ );
  15. ?>

The weak data type of php makes it simple and flexible to use php. However, it is also a sword of damaklis, and it is precisely because of the characteristics of the weak data type of php, when writing php code, developers need to pay more attention to changes in variable data types, especially when passing variables as function parameters. after all, most function parameters only want to be a specific data type. for example, in the following example, the type of parameters that the function sayHi () expects to receive is the Person object type. However, because php is not a strongly typed language and does not forcibly check the type of the variable, we can pass any type of parameters to the function, resulting in program errors or logical exceptions, the instance code is as follows:

  1. Class Person {
  2. Public $ name = 'codeplayer ';
  3. Public $ age = 3;
  4. }
  5. Function sayHi ($ person ){
  6. Echo "Hello! My name is $ person-> name. I'm $ person-> age years old .";
  7. }
  8. $ P = 'Zhang San ';
  9. SayHi ($ p); // if it is not the expected Person object type, a Notice-level error message will appear and the program continues to run.
  10. Echo 'suffix '; // The text is still output.
  11. ?>

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:

  1. Class Person {
  2. Public $ name = 'codeplayer ';
  3. Public $ age = 3;
  4. }
  5. Function sayHi (Person $ person ){
  6. Echo "Hello! My name is $ person-> name. I'm $ person-> age years old .";
  7. }
  8. $ Person = 'Zhang San ';
  9. SayHi ($ person); // It is not the expected Person object type, causing a Fatal Error and program termination
  10. Echo 'suffix '; // does not output the text information and the program stops running.
  11. ?>

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 Example code:

  1. // The following class
  2. Class MyClass
  3. {
  4. /**
  5. * Test functions
  6. * The first parameter must be an object of the OtherClass class.
  7. */
  8. Public function test (OtherClass $ otherclass ){
  9. Echo $ otherclass-> var;
  10. }
  11.  
  12. /**
  13. * Another test function
  14. * The first parameter must be an array.
  15. */
  16. Public function test_array (array $ input_array ){
  17. Print_r ($ input_array );
  18. }
  19. }
  20. /**
  21. * The first parameter must be of the recursive type.
  22. */
  23. Public function test_interface (Traversable $ iterator ){
  24. Echo get_class ($ iterator );
  25. }
  26. /**
  27. * The first parameter must be of the callback type.
  28. */
  29. Public function test_callable (callable $ callback, $ data ){
  30. Call_user_func ($ callback, $ data );
  31. }
  32. }
  33. // OtherClass class definition
  34. Class OtherClass {
  35. Public $ var = 'Hello World ';
  36. }
  37. ?>

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

  1. // Two class objects
  2. $ Myclass = new MyClass;
  3. $ Otherclass = new OtherClass;
  4. // Fatal error: The first parameter must be an object of the OtherClass class.
  5. $ Myclass-> test ('Hello ');
  6. // Fatal error: The first parameter must be an instance of the OtherClass class.
  7. $ Foo = new stdClass;
  8. $ Myclass-> test ($ foo );
  9. // Fatal error: The first parameter cannot be null
  10. $ Myclass-> test (null );
  11. // Correct: output Hello World
  12. $ Myclass-> test ($ otherclass );
  13. // Fatal error: The first parameter must be an array
  14. $ Myclass-> test_array ('a string ');
  15. // Correct: output array
  16. $ Myclass-> test_array (array ('A', 'B', 'C '));
  17. // Correct: output ArrayObject
  18. $ Myclass-> test_interface (new ArrayObject (array ()));
  19. // Correct: output int (1)
  20. $ Myclass-> test_callable ('Var _ dump', 1 );
  21. ?>

The type constraint can also be used in functions, not only in member functions of the class. the code is as follows:

  1. // The following class
  2. Class MyClass {
  3. Public $ var = 'Hello World ';
  4. }
  5. /**
  6. * Test functions
  7. * The first parameter must be an object of the MyClass class.
  8. */
  9. Function MyFunction (MyClass $ foo ){
  10. Echo $ foo-> var;
  11. }
  12. // Correct
  13. $ Myclass = new MyClass;
  14. MyFunction ($ myclass );
  15. ?>

Type constraints allow NULL values:

  1. /* Accept NULL values */
  2. Function test (stdClass $ obj = NULL ){
  3. }
  4. Test (NULL );
  5. Test (new stdClass );
  6. ?>

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.