How to construct a PHP class

Source: Internet
Author: User

The construction method is a special method of the class, the main function is to complete the initialization of the new object.

Features of the construction method:

(1) no return value;

(2) When creating a new object for a class, the system automatically calls the constructor of the class to complete initialization of the new object.

(3) in PHP5, a class can have two forms of construction methods, __construct and class names (), and when two appear simultaneously, the first one is selected. Try to use the first form of the constructor.

Considerations of construction methods;

1. Once a constructor is customized, the default constructor is overwritten, and the custom constructor is used when creating the object.

2. A class can have only one constructor and cannot be overloaded.

3. The default access modifier for the construction method is public

Example: When creating a human class, initialize $name and $age

Cases:

<?php
Class person{
Public $name;
Public $age;
The construction method of PHP5
Public Function __construct () {
echo "I am the construction method!";
}
/*//PHP4, the name and class name are the same
Public Function person () {
echo "PhP4 Method of construction!";
}
*/
}
$p 1=new person ();
?>

How to understand $this?

1, $this in nature can be understood to be the address of this object;

2, which object uses to $this, is which object's address;

3, $this can not be used outside the class.

Example 2:

<?php
Class person{
Public $name;
Public $age;
Public Function __construct () {
The system assigns each object a this, representing the current object
$this->name= "www.bianceng.cn";
$this->age=10;
}
}
$p 1=new person ();
echo "$p 1->name is". $p 1->age. "Years old!";
?>

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.