简体   繁体   中英

Does it make sense to check variable before initalizie it?

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();
        }
    }

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.

除非$ user是静态的,并且您正在尝试实现Singleton模式,否则不需要这样做。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM