<?php
class Ren
{
private $name;
private $sex;
private $age; //年龄必须在18-50之间
function __construct($v)
{
$this->sex = $v;
}
//魔术方法set
function __set($n,$v)
{
if($n=="age")
{
if($v>=18 && $v<=50)
{
$this->$n = $v;
}
}
else
{
$this->$n = $v;
}
}
//魔术方法get
function __get($n)
{
return $this->$n;
}
/*//设置age的值
function setage($a)
{
if($a>=18 && $a<=50)
{
$this->age = $a;
}
}
//获取age的值
function getage()
{
return $this->age;
}*/
function say()
{
echo "hello";
}
//析构方法
function __destruct()
{
echo "这是一个析构方法";
}
function __tostring()
{
return "这个类是人类";
}
}
$r = new Ren("男");
//$r->setage(20);
//echo $r->getage();
$r->say();
//$r->age = 30;
//echo $r->age;
//$r->__get("age");
//$r->__set("age",20);
var_dump($r);
//构造方法:写法特殊,执行时间特殊
//OOP三大特性:封装,继承,多态
//封装的目的:为了让类更安全
//封装的做法:
//1.类里面的成员变量做为private
//2.使用成员方法来间接访问成员变量
//3.在该方法里面加限制条件
//php类里面不允许出现同名方法
//函数重载
//在类里面写多个同名方法来实现不同功能
/*public string Show()
{
return "显示";
}
public string Show(string a)
{
return a+"显示";
}
public string Show(string a,string b)
{
return a+b+"显示";
}
public string Show(int b)
{
return b+"数字";
}*/
//1.函数名必须相同
//2.参数个数不同或参数类型不同
//例子:求两个圆之间的阴影面积
/*$maxr = 20;
$minr = 10;
$mj = 3.14*$maxr*$maxr - 3.14*$minr*$minr;
class Yuan
{
//代表半径
public $r;
function __construct($n)
{
$this->r = $n;
}
//求面积的方法
function MJ()
{
return 3.14*$this->r*$this->r;
}
}
$r1 = new Yuan(20);
$r2 = new Yuan(10);
$mianji = $r1->MJ()-$r2->MJ();*/
//例子:计算器
$a = 10;
$b = 5;
$jia = $a+$b;
$jian = $a-$b;
$cheng = $a*$b;
$chu = $a/$b;
class jisuan
{
public $a;
public $b;
function __construct($n,$m)
{
$this->a = $n;
$this->b = $m;
}
function jia()
{
return $this->a+$this->b;
}
function jian()
{
return $this->a-$this->b;
}
function cheng()
{
return $this->a*$this->b;
}
function chu()
{
return $this->a/$this->b;
}
function quyu()
{
return $this->a%$this->b;
}
}
$j = new jisuan(10,5);
$j->quyu();
?>