PHP advanced course notes object-oriented

Source: Internet
Author: User
The first section describes the basic knowledge of object-oriented, including class encapsulation, class inheritance, object, class definition and usage, class structure, and member methods, the source code of several examples is provided for reference only. Example 1:

The code is as follows:


// Class definition
Class User
{
// Attribute. Note the scope of public, private, and protected.
Public $ name = "hackbaby ";
// Constructor
Function _ construct ()
{
Echo "construct
";
}
// Method
Function say ()
{
Echo "this is called in the class itself: $ this-> name ";
}
// Destructor
Function _ destruct ()
{
Echo "destruct ";
}
// Return the description of the current object. call the instantiated variable name, for example, $ user in this example.
Function _ toString ()
{
Return "user class ";
}
}
// Instantiate. if The constructor has parameters, use $ user = new User ('parameter ');
$ User = new User ();
Echo $ user-> name ."

";
$ User-> say ();
Echo" ";
Echo $ user;
?>


Example 2:

The code is as follows:


Class Fruit
{
Protected $ fruit_color;
Protected $ fruit_size;

Function setcolor ($ color)
{
$ This-> fruit_color = $ color;
}

Function getcolor ()
{
Return $ this-> fruit_color;
}

Function setsize ($ size)
{
$ This-> fruit_size = $ size;
}

Function getsize ()
{
Return $ this-> fruit_size;
}

Function save ()
{
// Code
}
}
Class apple extends Fruit
{
Private $ variety;

Function setvariety ($ type)
{
$ This-> variety = $ type;
}

Function getvariety ()
{
Return $ this-> variety;
}
}
$ Apple = new apple ();
Echo $ apple-> setvariety ('redfu ');
Echo $ apple-> getvariety ();
Echo"
";
Echo $ apple-> setcolor ('red ');
Echo $ apple-> getcolor ();
Echo"
";
Echo $ apple-> setsize ('mega ');
Echo $ apple-> getsize ();

?>

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.