An example of PHP object orientation

  • 2020-03-31 21:38:16
  • OfStack

 
<?php 
class person{ 
//Below are the member properties of people
var $name; 
//The name of the person
var $sex; 
//A person's sex
var $age; 
//A person's age
//Define a constructor parameter as name $name, sex $sex, and age $age
function __construct($name,$sex,$age){ 
//$name passed in through the constructor to the member property $this-> Name is assigned an initial value
$this->name=$name; 
//$sex passed in by constructor to member attribute $this-> sex
$this->sex=$sex; 
//$age passed in through the constructor to the member property $this-> Age is assigned an initial value
$this->age="$age"; 
} 
//The following is the member method for people
function say() 
//The way this person can talk
{ 
echo " My name is: ".$this->name." Sex; ".$this->sex." My age is: ".$this->age."<br>"; 
} 
function run() //The way this person can walk
{ 
echo " The man is walking "; 
} 
//This is a destructor called before the object is destroyed
function __destruct() 
{ 
echo " goodbye ".$this->name."<br>"; 
} 
} 
//Three objects,$p1,$p2 and $p3, are created through the constructor method, and three different arguments are passed in, namely, name, gender and age
$p1=new person(" Xiao Ming "," male ",20); 
$p2=new person(" The bear "," female ",30); 
$p3=new person(" sunflower "," male ",25); 
//Now access the way the three objects speak $p1-> Say (); $p2 -> Say (); $p3 -> Say ();
?> 

The output result is:
My name is: xiaoming gender; Male my age is: 20
My name is: bear sex; Female my age is: 30
My name is: sunkui gender; Male my age is: 25
Goodbye sunflowers
See you bear
Goodbye, xiao Ming

Related articles: