567   PHP

一,魔术方法

1,__construct()
在实例化对象是被调用

2,__destruct()
在删除实例时被调用

3,__get()
在访问对象中非公有属性时会被调用,一般用来获取对象的私有和受保护的属性

4,__set()
在设置对象中非公有属性时会被调用,一般用来设置对象的私有和受保护的属性

5,__isset()
在判断对象中非公有属性时会被调用,如果是公有属性,可以直接使用isset()

6,__unset()
在删除对象中非公有属性时会被调用,如果是公有属性,可以直接使用unset()

 

二,示例代码:

class test{
	//公有属性
	public $name;
	//私有属性
	private $mobile;
	
	//实例化对象时被调用
	public function __construct() {
		echo 'initializing',"\n";
	}

	//删除对象时被调用
	public function __destruct(){
		echo 'unset obj',"\n";
	}
	
	// 获取非公有属性的值
	public function __get($name){
		echo 'get not public arguments',"\n";
		
		return $this->$name;
	}
	// 设置非公有属性的值
	public function __set($name,$value){
		echo 'set not public arguments',"\n";
		$this->$name = $value;
	}
	
	// 判断非公有属性
	public function __isset($name){
		echo 'isset not public arguments',"\n";
		if(isset($name)){
			return true;
		}else{
			return false;
		}
	}
	
	// 删除非公有属性
	public function __unset($name){
		echo 'unset not public arguments',"\n";
		unset($name);
		
	}


}
$test = new test();
echo 'set public name',"\n";
$test->name='hello';

echo "\n";
echo 'set private mobile',"\n";
$test->mobile='123456789';

echo "\n";
echo 'get public name',"\n";
echo $test->name,"\n";

echo "\n";
echo 'get private mobile',"\n";
echo $test->mobile,"\n";

echo "\n";
echo 'isset public name',"\n";
if(isset($test->name)){
	echo 'name is set',"\n"; 
}else{
	echo 'name is not set',"\n";
}

echo "\n";
echo 'isset private mobile',"\n";
if(isset($test->mobile)){
	echo 'mobile is set',"\n"; 
}else{
	echo 'mobile is not set',"\n";
}

echo "\n";
echo 'unset public name',"\n";
unset($test->name);

echo "\n";
echo 'unset private mobile',"\n";

echo "\n";
unset($test->mobile);
echo 'unset',"\n";
unset($test);

 

三,测试结果

 

initializing
set public name

set private mobile
set not public arguments

get public name
hello

get private mobile
get not public arguments
123456789

isset public name
name is set

isset private mobile
isset not public arguments
mobile is set

unset public name

unset private mobile

unset not public arguments
unset
unset obj




Leave a Reply

Your email address will not be published. Required fields are marked *