+ -
当前位置:首页 → 问答吧 → 【简单问题】类里 __set() __get() 不会被执行?!!

【简单问题】类里 __set() __get() 不会被执行?!!

时间:2011-12-09

来源:互联网

PHP code


class className{
    public $attribute;
    
    function __construct()
    {
        $this->attribute=123;
    }

    /*function __get($name)
    {
        echo "__get()done!";
        return $this->$name++;
    }
    */
        
        //这东西无效?!
    function __set($name,$value)
    {
        echo "__set()done!";
        if(($name="attribute")&&($value>=0)&&($value<=100))
            $this->$name=$value;
        return 1;
    }
}



$formValue=50000;

//if($formValue!=null)
//{
    $a=new className();
    echo "first".$a->attribute."<br/>";
    if($a->attribute=$formValue)
    if($a->attribute==$formValue)
        echo "设置成功!";
    $a->attribute."|";//按理说这样就可以直接输出属性值了,不是么???构造函数是没问题的。
    echo "".$a->attribute;
//}


作者: layerbase   发布时间: 2011-12-09

你的 attribute 属性时公共的,当然就不行了
__get、__set 只在属性不存在或为保护protected;或为私有private 时才会起作用

作者: xuzuning   发布时间: 2011-12-09

调用不存在的情况才会调用__set

PHP code

<?php
class className{
    public $attribute;
    
    function __construct()
    {
        $this->attribute=123;
    }

    /*function __get($name)
    {
        echo "__get()done!";
        return $this->$name++;
    }
    */
        
        //这东西无效?!
    function __set($name,$value)
    {
        echo "__set()done!";
       // if(($name="attribute")&&($value>=0)&&($value<=100))
            $this->$name=$value;
        return 1;
    }
}



    $formValue=50;
 
    $a=new className();
    echo "first".$a->attribute."<br/>";
    if($a->attribute=$formValue)
    if($a->attribute==$formValue) echo "设置成功!";

    $a->attribute."|";
    echo "".$a->attribute;

    $a->a = 40;
    echo $a->a;

 


作者: ci1699   发布时间: 2011-12-09

相关阅读 更多