php面向对象之__set(),__get(),tostring()魔术方法;

class test
{
    public $x;
	private $y;
	function __set($name,$value)//此方法当对象给一个不存在的属性或者私有,受保护属性赋值时会调用的,可以动态的给属性赋值;
	{
	    $this->$name=$value+10;
	}
	function __get($key)//此方法当对象获取一个不存在的属性或者私有,受保护属性值时会调用的,可以动态的返回属性的值;
	{
	     if(isset($this->$key))
		 {
		     return $this->$key;
		 }
		 else
		 {
			   return '没有次属性';
		 }
	}
        function __toString()//此方法在echo一个对象时调用的
	{
	   return 'haha'; 
	}

}
$te=new test();
$te->y=9;
echo $te->y;echo '<br />';
$te->z=12;
echo $te->z;
echo $te;//输出 haha

  

posted @ 2013-03-18 11:22  qingq  阅读(185)  评论(0编辑  收藏  举报