PHP Parameter Type restrictions

Source: Internet
Author: User
PHP, like other languages (Oc,java), also introduces the checking of parameter types, but PHP has only two qualified types of arrays and objects, and there are no qualified types such as String or integer. Parameter type restriction, this is the interface, abstract class, function, method, can be used in 5.3+ or above, but only two types of array object are declared at present.

The benefits of doing this:

①: Can coordinate the coding, at least I don't have to look at the comments or code, I know what parameters to pass in.

②: Using a type declaration for an incoming object, you do not need to use the IS_A function inside a function to identify whether the incoming object is legitimate and to pass the screening work to the compiler for completion

Is_a-Returns TRUE if the object belongs to the class or if the class is the parent class of this object

Class user{public     $name;     public $password;     function __construct ($name, $password) {         $this->name= $name;         $this->password= $password;     } The}//parameter can specify the object type function f1 (User $user) {     echo $user->name, ",", $user->password;} Parameter can specify the array type function F2 (array $arr) {}//parameter can not specify a base type, the following sentence will be faulted function F3 (String $s) {}

OK, next verify:

When a string is passed to the F1 () function, an error is given:

$a = ' Xiaojun ';

$ret = F1 ($a);


PHP catchable fatal Error:argument 1 passed to F1 () must is an instance of User, string given, called In/tmp/f921205b-ef 87-4aa8-b715-a131af661abd/code on line + defined In/tmp/f921205b-ef87-4aa8-b715-a131af661abd/code on line 11

The error description is clear and a user instantiation object must be passed to the function.

This is the right thing to do:

Instantiate the object and initialize $user_obj = new User ("Kaiyi", ' 123456 '); $ret = F1 ($user _obj);

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