Jump to content

private property vs getProperty with static variable


koen

Recommended Posts

Suppose you're working in a database class and every method in this class needs the database connection. A common solution is to to use somethink like this

 

private $db;

public method getPosts()
{
    $db = $this->getConnection();
    $db->execute( // some sql here);
}

private method getConnection()
{
    if (is_null($this->db) $this->db = // stuff to get connection
    return $this->db;
}

 

This doesn't prevent methods from calling $this->db directly. Encapsulation is mostly viewed between objects but not in the object itself.  To prevent methods from accessing $this->db a solution would be the following:

 

private method getConnection()
{
    static $db;
    if (is_null($db) $db = // stuff to get connection
    return $db;
}

 

Is there a reason the first one is used and not the second one?

Link to comment
Share on other sites

I don't see any big problems with that, given that you indeed want the variable to be static.

 

Ie, "static $db" does not (more or less - it's more confined) equal "private $db", but rather "static private $db".

 

There is one tiny issue though: the presence of the variable is less transparent. But, if you can live with that, and it's worth the added level of encapsulation, knock yourself out I'd say.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.