Example one: To find the area of a circle, big circle Radius: 10 Small Circle Radius: 5
To create a circle class:
1 classYuan2 {3 Public $r;4 function__construct ($r)//RADIUS Initialization5 {6 $this->r=$r;7 }8 functionMianji ()//returns the area of a circle9 {Ten return $this->r*$this->r*3.14; One } A}
Instantiate two circles and ask for an area
1 include ("Yuan.class.php"); // calling a circle class using the Load Class 2 $y 1=new Yuan (ten); // instantiate a great circle 3 $y 2=new Yuan (5); // instantiate a small circle 4 Echo $y 2->mianji ()-$y 1->mianji (); // the area of the output circle
Example two: outputting a table with an object-oriented approach
class to build a table
1 classInfo2 {3 Public $code;4 Public $name;5 Public $sex;6 Public $nation;7 Public $birthday;8}
Assign a value to each member variable and output
1 include("Info.class.php");2 3 $attr=Array();4 5 $info 1=NewInfo ();6 $info 1->code= "P001";7 $info 1->name= "Zhang San";8 $info 1->sex= "Male";9 $info 1->nation= "Han";Ten $info 1->birthday = "1988-2-3"; One //append elements to an array A Array_push($attr,$info 1); - - $info 2=NewInfo (); the $info 2->code= "P002"; - $info 2->name= "John Doe"; - $info 2->sex= "Female"; - $info 2->nation= "Han"; + $info 2->birthday = "1989-2-3"; - Array_push($attr,$info 2); + A $info 3=NewInfo (); at $info 3->code= "P003"; - $info 3->name= "Harry"; - $info 3->sex= "Male"; - $info 3->nation= "Hui"; - $info 3->birthday = "1990-2-3"; - Array_push($attr,$info 3); in Echo"<table width= ' 100% ' border= ' 1 ' cellpadding= ' 0 ' cellspacing= ' 0 ' >"; - //output Table to Echo"<tr><td> Code </td><td> name </td><td> Gender </td><td> National </TD><TD > Birthday </td></tr> ";//Output first column + foreach($attr as $v)//iterating through an array - { the Echo"<tr><td>{$v->code}</td><td>{$v->name}</td><td>{$v->sex}</td><td>{$v->nation}</td><td>{$v->birthday}</td></tr> "; * } $ Echo"</table>";
PHP Object-oriented practice