views:

1519

answers:

3

I've had a good read of the PHP specs on overloading, and most of the examples appear to be intended to simply allow defining of custom fields (similar to stdClass).

But what about the private fields defined in my class? How should these be retrieved/assigned? I could do a switch on possible values and act on certain values:

class A
{
    private $name;
    private $age;

    public function __get( $var )
    {
        switch ( $var )
        {
            case 'name':
                return $this->name;
                break;
            case 'age':
                return $this->age+10; // just to do something different ;)
                break;
            default:
                break;
        }
    }
}

Is this the best method, or is there another generally accepted best practice? (I don't know if it's possible to loop class variables inside a class, but regardless that's not appropriate in most situations since you don't want to return everything.)

+1  A: 

I don't see many people using them, but here is what I think.

For retrieving private variables, you probably want to give a list of defined variables that are able to be accessed by the outside. Then, check to see if the requested variable is in that array. If it is, allow it to be changed/gotten. If not, either error or return null.

Honestly, the implementations for this are really case-by-case. If you had a user class that you stored all the info in a single array, you could have $user->name be pulled from $user->account['name'], or something like that.

Also, in a more case-by-case, you could do some modification before giving them values, like hashing a password.

Chacha102
+1  A: 

This would effectively make them public, and usually this gains you nothing over simply using public properties (but you pay performance penalty and have to write more code, risk bugs).

Use that only if you have existing code that uses public property and you suddenly need getter/setter for it (like your example with age).

If you need to execute some code when property is read/written (e.g. make it read-only or lazily fetch from the database), then you should use normal getters/setters (getAge()/setAge()).

porneL
It gains me a lot. My classes have a lot of properties which come from different tables, and an individual script execution (read: trip to the server) is only going to be interested in a very small subset of them. I use __get() to only fetch them once, when they are referenced (I also at the same time fetch any other properties that available from the same query). On a high volume site, this method has drastically reduced database access. I can also impose security on each property, based on the session's role.
grantwparks
@grantwparks: I think that falls under "unless you need getter/setter" exception.
porneL
+3  A: 
grantwparks