A php Object-oriented example. For more information about php Objects, see.
The code is as follows:
Class person {
// The following are the member attributes of a person.
Var $ name;
// Name of the person
Var $ sex;
// Gender of a person
Var $ age;
// Age of the person
// Define a constructor parameter as name $ name, gender $ sex and age $ age
Function _ construct ($ name, $ sex, $ age ){
// Assign the initial value to the member attribute $ this-> name through the $ name passed in by the constructor
$ This-> name = $ name;
// Assign the initial value of $ sex to the member attribute $ this-> sex passed in through the constructor
$ This-> sex = $ sex;
// Assign an initial value to the member attribute $ this-> age through the $ age passed in by the constructor
$ This-> age = "$ age ";
}
// The following is the member method of a person.
Function say ()
// How this person can speak
{
Echo "My name is :". $ this-> name. "Gender ;". $ this-> sex. "My age is :". $ this-> age."
";
}
Function run () // this person can walk
{
Echo "this person is walking ";
}
// This is a destructor called before the object is destroyed.
Function _ destruct ()
{
Echo "goodbye". $ this-> name ."
";
}
}
// Create three objects $ p1, $ p2, and $ p3 by using the constructor method, and input three different real parameters as name gender and age respectively.
$ P1 = new person ("James", "male", 20 );
$ P2 = new person ("Bear", "female", 30 );
$ P3 = new person ("sunflower", "male", 25 );
// How to access the following three objects: $ p1-> say (); $ p2-> say (); $ p3-> say ();
?>
Output result:
My name is James gender; my male age is: 20
My name is: Bear gender; female: 30
My name is: Sunflower gender; male's age is: 25
Goodbye sunflower
Goodbye Bear
Goodbye James