PHP封装
类的概念
对象的概念
定义类
class Ren
{
	//成员变量
	//成员方法
}
造对象
$r = new Ren();
调用对象的成员$r->
面向对象三大特性:封装,继承,多态
1.封装
目的:让类更加的安全。做法:不让外界直接访问类的成员
具体做法:
1.成员变为私有:访问修饰符(public private protected)
2.造成员方法来操作变量,构造函数
3.使用类里面提供的__get()和__set()方法
class Ren
{
	private $age; //私有成员
	private $name;
	private $sex;
	
	//构造函数:在造对象的时候,对成员变量进行初始化
	//1.执行时间特殊:造对象的时候就自动执行 
	//2.写法特殊:__construct
	
	function __construct($s)
	{
		$this->sex = $s;
	}
	
	//造方法去给变量$age赋值
	/*public function SetAge($a)
	{
		if($a>18 and $a<50)
		{
			$this->age = $a;
		}
	}
	//取值
	function GetAge()
	{
		return $this->age;
	}*/
	
	
	
	//变量赋值的方法
	function __set($n,$v)
	{
		if($n=="age")
		{
			if($v>18 and $v<50)
			{
				$this->$n = $v;
			}
		}
		else
		{
			$this->$n = $v;
		}
	}
	//取值方法
	function __get($n)
	{
		return $this->$n;
	}
	
	
}
$r = new Ren("男");
$r->name = "张三";
var_dump($r);
<?php
class YunSuan
{
	private $a;
	private $b;
	function __construct($a,$b)
	{
		$this->a=$a;
		$this->b=$b;
	}
	function __set($n,$v)//name和value值
	{
		if($v>0 && $v<100)
		{
			$this->$n=$v;
		}
	}
	function __get($n)//变量名称
	{
		return $this->$n;	
	}
	function He()
	{
		return $this->a+$this->b;
	}
	function Cheng()
	{
		return $this->a*$this->b;
	}
	function Chu()
	{
		return $this->a/$this->b;
	}
}
$r=new YunSuan(5,2);
echo ($r->a+$r->b);
                    
                
                
            
        
浙公网安备 33010602011771号