douba9425 2010-10-18 16:33 采纳率: 100%
浏览 21
已采纳

在initalizie之前检查变量是否有意义呢?

Is there any advantage if i check if the object already exists in an language like php?

    /**
     * User object
     * @var My_Model_User
     */
    protected $user = null;


    /**
     * Setup
     */
    public function __construct()
    {
        if ($this->user === null) {
            $this->user = new stdClass();
        }
    }
  • 写回答

2条回答 默认 最新

  • duanhuokuang5280 2010-10-18 16:37
    关注

    In your particular example it doesn't make any sense, because the constructor is the first method to be executed. So before, the object doesn't exist, so the members of it don't exist either, so you are fine with simply assuming that the variable still holds its initial value.

    If you however use variables that are meant to change during the usage with your object, then it might be a good idea to check the existance of those for critical parts. For example when you have a connection object for some server connection and it is possible to close the connection without destroying your object (that holds that connection), then it would be a good idea to check if the connection still exists whenever you want to access it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题