dongxie2613 2011-02-25 16:44
浏览 44
已采纳

PHP:无法在对象方法中设置对象属性?

This should be so easy. I have a PHP class that has custom methods to return information about objects. I want to use the custom methods to determine whether or not a specific parameter has been set in the object. If it's set, return the property. If not, the method should contact the database to get the information and set the object's property.

However each time I run the code below, it appears that the object's property does not get set. The retrieve_user_first_name method hits the database access object every time.

I've tried checking the value of the property using is_null, empty, isset. I'm feeling like a dope.

require_once('dbaccess.class.php');

class User {
    protected $user_id;
    protected $first_name;  

function __construct($user_id) 
    {
    $this->user_id = $user_id;  

    }

function __get($variablename)
    {
    return $this->$variablename;
    }

function __set($variablename, $variablevalue)
    {
    $this->$variablename = $variablevalue;
    }

function __destruct()
    {

    }

function retrieve_user_first_name() 
    {       
    if(!isset($this->first_name)) {
        $dbAccess = new DBAccess();
        $strFirstName = $dbAccess->retrieve_user_first_name($this->user_id);
        $this->first_name = $strFirstName;
    }
    else {
        $strFirstName = $this->first_name;  
    }
    return $strFirstName;
    }

}
  • 写回答

1条回答 默认 最新

  • dovhpmnm31216 2011-02-25 17:20
    关注

    The code you posted works fine.

    I think the problem is that you are not using the same object for your sequential calls in whatever code is accessing this object.

    So something like:

    $ob = new User();
    $ob->retrieve_user_first_name();
    
    $ob = new User();
    print $ob->first_name;
    

    is happening. Obviously, it's probably not so blatant, but that's the simplest explanation for your problem.

    The only other option, given the code you posted, is that all of your database calls are returning empty strings or failing, so the variable is never getting updated. This is a very good possibility, so check both of these options in your code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题