PHP5 type Constraint Learning notes

Source: Internet
Author: User
Tags class definition php code terminates

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

The code is as follows Copy Code

 

 <?php
    class Person {
      
   

    $a = 1;//At this point, the $a is an integer type (integer)
    var_dump ($a);
    $a = 1.0; At this point, the $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.111cn.net '); At this point, $a array type (array)
    var_dump ($a);
    $a = new person ();//At this point, the $a is the Person object type ( Object)
    var_dump ($a);
    $a = mysql_connect (' localhost ', ' username ', ' Password ');   //At this point, the $a is the resource type (Resource)
    var_dump ($a);
   ?

 

The corresponding run effect is shown in the following illustration:


PHP's weak data types make PHP easy and flexible to use. However, this is also a sword of Damocles. It is precisely because of the characteristics of PHP weak data types, in the writing of PHP code, developers need to pay attention to the variable data types of changes, especially variables as a function of the parameters to pass, more attention to this point. After all, most of the function parameters are expected to be only a certain type of data. 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 since PHP is not a strongly typed language and does not force a check on the type of the variable, we can pass parameters of any type to the function, causing the program to complain or to have logic anomalies

  code is as follows copy code

    <?php
    class Person {
 & nbsp;      Public $name = ' Codeplayer ';
        Public $age = 3;
   }

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

    $p = ' John ';
    Sayhi ($p);//Not expected person object type, notice level error message appears, program continues to run
    echo ' Suffix '; /Still output the text information
   

Starting with PHP 5, we can use the new type constraint mechanism to type constraints on some of the data types of the function arguments. Also, take the above code as an example, we can write the Sayhi () function requires that the passed in parameter must be a person object type, or else a fatal error (Fatal error), and terminate the current page script run. To use the type constraint mechanism of PHP is very simple, we only need to add the specified type name before the parameter variable declared by the function. When we call the function, PHP forces it to check whether the parameter of the function is of the specified type and raises a fatal error if it is not the specified type.

  code is as follows copy code

    <?php
    class Person {
 & nbsp;      Public $name = ' Codeplayer ';
        Public $age = 3;
   }

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

    $person = ' John ';
    Sayhi ($person);//Not expected person object type, throws fatal error fatal error, program terminates
    Echo Suffix '; The text information is not printed and the program terminates
   

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


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

Example #1 Type Constraint example

The code is as follows Copy Code

<?php
such as the following class
Class MyClass
{
/**
* Test function
* The first argument must be an object of the Otherclass class
*/
Public function test (Otherclass $otherclass) {
Echo $otherclass->var;
}


/**
* Another test function
* The first argument must be an array
*/
Public function Test_array (array $input _array) {
Print_r ($input _array);
}
}

/**
* The first argument 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";
}
?>

When a function calls an argument that is inconsistent with a defined parameter type, a fatal error that can be caught is thrown.

  code is as follows copy code
<?php
//Two class objects
$myclass = new MyClass;
$otherclass = new Othercla SS;

//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: 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);
?

A type constraint is not only used in a member function of a class, but also in a function:

The code is as follows Copy Code

<?php
such as the following class
Class MyClass {
Public $var = "Hello World";
}

/**
* Test function
* The first argument 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:

<?php

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

}

Test (NULL);
Test (new StdClass);

?>

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.