koen Posted March 1, 2008 Share Posted March 1, 2008 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? Quote Link to comment https://forums.phpfreaks.com/topic/93854-private-property-vs-getproperty-with-static-variable/ Share on other sites More sharing options...
448191 Posted March 1, 2008 Share Posted March 1, 2008 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. Quote Link to comment https://forums.phpfreaks.com/topic/93854-private-property-vs-getproperty-with-static-variable/#findComment-480907 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.