php 给对象私有及受保护的成员变量赋值的几种方法

1.构造方法赋值

_cityName = $_cityName;
		$this->_population = $_population;
	}
	
	public function getCityName(){
		return $this->_cityName;
	}
	
	public function getPopulation(){
		return $this->_population;
	}
}

$nanjing = new City('南京',10000000);
echo '城市:'.$nanjing->getCityName(),'
'; //城市:南京 echo '人口:'.$nanjing->getPopulation(),'
'; //人口:10000000


2.魔术方式赋值和调用:__set()、__get()

_cityName='苏州' ---无权访问权限--> __set('_cityName','苏州');
	**/
	public function __set($property_name,$property_value){
		$this->$property_name = $property_value;
	}
	
	//magic method: __get()
	/**
	当我们调用一个权限上不允许访问的属性或者是不存在的属性时,__get()魔术方法会自动调用,并且自动传参,参数名是属性名
	$suzhou->_cityName ---无访问权限--> __get(_cityName);
	**/
	public function __get($property_name){
		if(isset($this->$property_name)){
			return $this->$property_name;	
		}else{
			return null;
		}
		
	}
}


//设置__set()和__get()方法,可以在类外部像给public修饰的成员变量一样赋值和调用
$suzhou = new City();
$suzhou->_cityName = '苏州';  
$suzhou->_population = 7000000;
echo '城市:'.$suzhou->_cityName,'
'; //城市:苏州 echo '人口:'.$suzhou->_population,'
'; //人口:7000000


3.调用类常规方法传参赋值

_cityName = $_cityName; 
	}
	
	function setPopulation($_population){
		$this->_population = $_population;
	}
	
	function getCityName(){
		return $this->_cityName;
	}
	
	function getPopulation(){
		return $this->_population;
	}

	
	//
	function set($name,$value){
		$this->_factory[$name] = $value;//以数组的形式存储变量赋值
	}
	
	function get($name){
		return $this->_factory[$name];
	}
}


$shanghai = new City();
//通过函数传参的形式给对象指定私有变量赋值,通过指定函数获取指定私有变量值
$shanghai->setCityName('上海'); 
$shanghai->setPopulation(30000000);
echo '城市:'.$shanghai->getCityName(),'
'; //城市:上海 echo '人口:'.$shanghai->getPopulation(),'
'; //人口:30000000 $shanghai->set('totalArea','6340平方公里'); $shanghai->set('areaCode','017'); $shanghai->set('zipCode',200000); echo '面积:'.$shanghai->get('totalArea'),'
'; //面积:6340平方公里 echo '区号:'.$shanghai->get('areaCode'),'
'; //区号:017 echo '邮编:'.$shanghai->get('zipCode'),'
'; //邮编:200000


你可能感兴趣的:(PHP)