On Wed, Aug 15, 2012 at 11:33 AM, Paul M Foster <paulf@xxxxxxxxxxxxxxxxx> wrote: > On Wed, Aug 15, 2012 at 09:28:28AM +0100, phplist wrote: > >> This relates to a minor dilemma I come across from time and time, >> and I'm looking for advice on pros and cons and best practice. Last >> night I encountered it again. >> >> Within a site I have a User object, and within page code would like to have >> if ($crntUser->isASubscriber) {...} >> >> There seems to be two ways to handle this: >> >> I can have a User object method "getSubscriberStatus()" which sets >> $this->isASubscriber. But to use this I would have to run the method >> just before the if statement. >> >> Or I could have a method "isASubscriber()" which returns the result, >> meaning the if statement should be >> if ($crntUser->isASubscriber()) {...} >> >> While this is last night's specific example, I seem to face the >> method-setting-variable or the method-returning-result-directly >> decision quite often. >> >> Is either of these approaches preferable, or does it simply not matter? > > If I read you correctly, the latter would be preferable, primarily > because it involves one less step. But if you're going to have to make > that decision in an "if" statement repeatedly, I'd probably say: > > $isSubscribed = $crntUser->isASubscriber(); > > just because in subsequent code, you're not suffering the (admittedly > small) repeated overhead of the function call. > > But in answer to your question, isASubscriber() would be a pretty > standard "getter" method to expose internal object properties. > > Paul I generally use this "getter" method as well. If it bothers the OP that isASubscriber() is a "method" rather than a "property," one could use the magic __get method: <?php class User { private $isASubscriber = false; public function __get($property) { if ('isASubscriber' === $property) { return $this->isASubscriber; } } } ?> In the end, it is still a function call either way though. The advantage I see to both of these method-based approaches versus exposing the property as public is that these methods prevent code outside your class from doing something stupid: <?php $u = new User(); $u->isASubscriber = 'rutabaga'; // Fatal error: Cannot access private property User::$isASubscriber ?> (Yes, I have seen proof that it is TECHNICALLY possible to get around this in PHP, for example with unserialize.) Andrew -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php