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 ();
?>