Question

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.)

Was it helpful?

Solution

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()).

OTHER TIPS

I make extensive use of __get() and __set() AND I have my properties declared public. I wanted the best of both worlds, so my IDE could list public properties for me when I type the name of a class instance. How did I get the PHP interceptor methods to work, even though the properties are public and visible outside the class?

unset() the properties I want __get() and __set() to be used for in the class __construct().

Figuring this method out took a couple evenings of frustration :-)

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top