php面向对象 练习

实例一:求一个圆环的面积,大圆半径:10    小圆半径:5

造一个圆的类:

 1 class Yuan
 2 {
 3       public  $r;
 4       function __construct($r)         //半径初始化
 5       {
 6              $this->r=$r;
 7       }
 8       function Mianji()                        //返回圆的面积
 9       {
10            return $this->r*$this->r*3.14;
11       }
12 }

实例化两个圆,并求面积

1 include ("Yuan.class.php");    //使用加载类调用圆的类
2 $y1=new Yuan(10);         //实例化一个大圆
3 $y2=new Yuan(5);           //实例化一个小圆
4 echo $y2->Mianji()-$y1->Mianji();     //输出圆的面积

实例二:用面向对象的方法输出一个表格

建一个表的类

1 class Info
2 {
3     public $code;
4     public $name;
5     public $sex;
6     public $nation;
7     public $birthday;
8 }

给每个成员变量赋值,并输出

 1 include("Info.class.php");
 2 
 3 $attr = array();
 4 
 5 $info1 = new Info();
 6 $info1->code="p001";
 7 $info1->name="张三";
 8 $info1->sex="男";
 9 $info1->nation="汉族";
10 $info1->birthday = "1988-2-3";
11 //往数组里面追加元素
12 array_push($attr,$info1);
13 
14 $info2 = new Info();
15 $info2->code="p002";
16 $info2->name="李四";
17 $info2->sex="女";
18 $info2->nation="汉族";
19 $info2->birthday = "1989-2-3";
20 array_push($attr,$info2);
21 
22 $info3 = new Info();
23 $info3->code="p003";
24 $info3->name="王五";
25 $info3->sex="男";
26 $info3->nation="回族";
27 $info3->birthday = "1990-2-3";
28 array_push($attr,$info3);
29 echo "<table width='100%' border='1' cellpadding='0' cellspacing='0'>";
30 //输出表
31 echo "<tr><td>代号</td><td>姓名</td><td>性别</td><td>民族</td><td>生日</td></tr>";    //输出第一列
32 foreach($attr as $v)     //遍历数组
33 {
34     echo "<tr><td>{$v->code}</td><td>{$v->name}</td><td>{$v->sex}</td><td>{$v->nation}</td><td>{$v->birthday}</td></tr>";
35 }
36 echo "</table>";
原文地址:https://www.cnblogs.com/zk0533/p/5452028.html