PHP面向对象的编程(类成员方法用法)

来源:互联网 发布:淘宝买电话卡 编辑:程序博客网 时间:2024/05/16 14:14
1、创建一个PIG类,包含属性名字,重量,颜色,年龄及类成员方法增加和减少体重,查看体重!
创建类 Pig.class.php:
<?php    class pig{//属性        public $name;public $weight;public $color;public $age;        //成员方法public function addWeight($a){               //  $weight+=$a; 这种方法是错误的,会认为$weight是新的变量!$this->weight+=$a;}public function minusWeight($a){           // $weight-=$a; 这种写法是错误的,   $this->weight-=$a;}public function showWeight(){            echo "猪的重量:$this->weight!<br/>";}    }?>
调用类 pig.php
<?php   //导入类   require_once "Pig.class.php";   //创建一个类   $pig1= new pig();   $pig1->weight=100;   $pig1->addWeight(10);   $pig1->showWeight();   $pig1->minusWeight(10);   $pig1->showWeight();?>

打开文件pig.php将显示下面的内容!

猪的重量:110!猪的重量:100!

2、实现下图的功能,要求封装成一个类!


   知识点:这里使用到一个隐藏域

  页面代码CatView.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head>  <title> 类的运用实例1 </title>  <meta http-equiv="content-type" content="text/html;charset=utf-8"> </head> <body>   <form action="Catwork.php" method="post">   <h1>四则运算</h1>   第一个数:<input type="text>" name="num1"/><br/>   第二个数:<input type="text>" name="num2"/><br/>   运算符号:   <select name="oper">   <option value="+">+</option>   <option value="-">-</option>   <option value="*">*</option>   <option value="/">/</option>   </select><br/>   <!--隐藏域-->   <input type="hidden" value="compute" name="doing" />   <input type="submit" value="点击计算"/><br/>  </form>   <br/><br/>   <!--再编程中为了区分不同的请求,使用隐藏域-->      <form action="Catwork.php" method="post">   <h1>圆运算</h1>   输入圆的半径:<input type="text>" name="radius"/><br/>   <input type="hidden" value="circularArea" name="doing"/>   <input type="submit" value="点击计算面积"/><br/>  </form> </body></html>

计算界面:
<?php    //导入类require_once "Cat.class.php";$cat1=new cat();    //这里首先接受doing 判断是四则运算还是圆面积计算$doing=$_REQUEST["doing"];    if($doing == "compute"){    $num1=$_REQUEST["num1"];    $num2=$_REQUEST["num2"];    $oper=$_REQUEST["oper"];    echo "四则运算结果:".$cat1->compute($num1,$num2,$oper);} else {$radius=$_REQUEST["radius"];echo "圆的面积是:".$cat1->circularArea($radius);}?>

类:
<?php    class cat{        //四则运算function compute($num1,$num2,$oper){           $res="";   switch($oper){           case "+": $res=$num1 + $num2; break;           case "-": $res=$num1 - $num2; break;           case "*": $res=$num1 * $num2; break;           case "/": $res=$num1 / $num2; break;           default: echo "错误运算符"; break;   }   return $res;        }function  circularArea($adius){           return 3.15*$adius*$adius;}    }?>