<meta charset="UTF-8">
<html>
<head>
<title>学生管理类</title>
</head>
<body>
<form method="post">
<table border="1" align="center" bgcolor="yellow">
<td>学号:<input type="text" name="number"><tr/></td>
<td>姓名:<input type="text" name="name"><tr/></td>
<td>性别:<input type="radio" name="sex" value="男" checked="checked">男
<input type="radio" name="sex" value="女">女<tr/></td>
<td align="center"><input type="submit" name="ok" value="显示"></td>
</table>
</form>
</body>
</html>
<?php
class student
{
private $number;
private $name;
private $sex;
function show($XH,$XM,$XB)
{
$this->number=$XH;
$this->name=$XM;
$this->sex=$XB;
echo "<table border='2' align='center' bgcolor='#fff8dc'>";
echo "<td>学号:".$this->number."<tr/></td>";
echo "<td>姓名:".$this->name."<tr/></td>";
echo "<td>性别:".$this->sex."<tr/></td>";
echo "</table>";
}
}
if(isset($_POST['ok']))
{
$XH=$_POST['number'];
$XM=$_POST['name'];
$XB=$_POST['sex'];
$stu=new student();
$stu->show($XH,$XM,$XB);
}
继承和组合方法的对比
<?php
class car{
public function addoil(){
echo "Add oil.<br>";
}
}
class vw extends car{} //继承比组合更少的代码量-但垂直复用(不灵活)
class gm{ //组合比继承多代码--但水平复用(更灵活)
public $car;
function __construct(){
$this->car=new car;
}
public function addoil(){
$this->car->addoil(); //拥有(组合)了类car的方法addoil
}
}
$vm=new vw();
$vm->addoil();
$gm=new gm();
$gm->addoil();
属性重载
<?php
class classname{
private $attribute1=1;
private $attribute2=2;
function __get($name){
if($name=='attribute1'||$name=='attribute2')
return $this->$name;
}
function __set($name, $value)
{
if($name=='attribute1'||$name=='attribute2')
$this->$name=$value;
}
}
$obj=new classname;
echo $obj->attribute1." ";
echo $obj->attribute2," ";
$obj->attribute2=19;
echo $obj->attribute2;
方法重载
<?php
class C_call{
function getarray($a){print_r($a);}
function getstr($str){echo $str;}
function __call($name, $array)
{
if($method=='show'){ //实际上是show的重载
if(is_array($array[0])) //$array是一个数组-$array[0]是第一个单元
$this->getarray($array[0]);
else
$this->getstr($array[0]);
}
}
}
$obj=new C_call;
$obj->show(array(1,2,3));
$obj->show('string');
$obj->getstr('ABC');