1

For example, if I had a Customer class and wanted to get all orders by them. Would it be better to do:

class Customer{
    public function getOrders(){
        return results from db query
    }
}

...

foreach($customer->getOrders()){}

or

class Customer{
    private function getOrders(){
        return results from db query
    }

    public function __get($attribute){
        if($attribute === 'orders'){
            return $this->getOrders();
        }
    }
}

...

foreach($customer->orders){}

The former isn't as bloated, but then it's nice to be able to access it as if it were a property rather than with getOrders().

  • 1
    what programming language is this, php? – gnat Apr 4 '16 at 16:41
  • PHP yes, although it would be applicable to all programming languages, no? – Cal7 Apr 4 '16 at 17:06
  • 1
    Only if returning results from the db query is a fast and cheap operation. – whatsisname Apr 4 '16 at 17:18
  • ...which it generally isn't considered to be for these purposes. – Robert Harvey Apr 4 '16 at 17:24
1

The __get magic method is completely fine, just make sure to couple it either with the @property (if you want a magic __set as well) or @property-read phpDoc annotation so consumers of your class know what they can expect from the public API of your class.

PHP's combination of __get and __set methods and the @property annotation is a poor-man's version of C#'s attributes and just like in C#, they're not bad as long as you show in the API of the class what the class actually offers (in C# you don't need the annotation for this, because the language supports attributes by default).

I personally don't use magic __set at all, but have been using __get to a great extent and have never had problems with the method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.