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?

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.