tags:

views:

26

answers:

2

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();
        }
    }
+1  A: 

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.

poke
+1  A: 

There's no need to do this unless $user is static, and you're trying to implement the Singleton pattern.

Alex Howansky