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.