PHP Object-Oriented Programming-Constructor

Source: Internet
Author: User

The basic syntax for customizing constructor methods in the class:

 
// PhP5
[Modifier] function _ construct ([parameter list]) {}
// PhP4
 
[Modifier] function class name ([parameter list]) {}

Reading a column is easy to understand:
<? PHP  Class  Person {  Public   $ Name  ;  Public   $ Age  ;  //  Constructor PhP5          Public  Function _ Construct ( $ Name , $ Age  ){  $ This -> Name = $ Name  ;  $ This -> Age = $ Age  ;}  //  The constructor PhP4 is written here as PhP5 is compatible with PhP4.          Public   Function Person ($ Name , $ Age  ){  $ This -> Name = $ Name  ;  $ This -> Age = $ Age  ;}}  $ P1 = New Person ("boss", 27 );  Echo   $ P1 ->Name;  $ P1 = New Person ("xiao'er", 26 );  $ P1 = New Person ("John", 24 ); ?>

Note:

$ This:

1. $ this is essentially the address of this object.

2. Which object is $ this, which is the object address?

3. $ this cannot be used outside the class Understanding of constructor:
    • The constructor name and class name are the same (PhP4) and PhP5 ConstructorThe name can be the same as the class name or _ construct ()
    • The default access modifier of the constructor is public, and the constructor does not return a value.
    • After a new object is created, the system automatically calls the constructor of this class.
    • A class has only one constructor. After PhP5, although _ construct () and Class Name () can coexist, only one construct () can be used.
    • For exampleIf no custom constructor is provided for the class, the class uses the default constructor..
    • If a constructor is defined for the class, the default constructor of the class is overwritten.
 


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.