You are not logged in.

#1 13 Aug 2009 9:31

Ethan
Lowter Staff
From: Minneapolis, MN
Registered: 20 Jan 2005
Posts: 6960
Message  Website

PHP Magic Getters and Setters

Lately, I've become a pretty big fan of PHP's magic getters and setters.  Basically, I never make class members public, so I'm stuck coding some sort of get() function to access anything.  However, using PHP overloading I've started to do this:

Code:

/**
 * @param string $member
 * @return string
 * @throws ResException When non-existant of non-accessible member is called
 */
public function __get($member)
{
    if (isset($this->_publicData[$member]))
    {
        return $this->_publicData[$member];
    }
    else
    {
        throw new ResException('$' . $member . ' does not exist or cannot be accessed.');
    }
}

Everything public is stuffed into some array and then then __get() access it.  That way publicly the syntax is nice, like $object->member.  Anyway, I thought I'd quickly share and get any thoughts.  It seems to work well at making applications a bit more maintainable.


Ethan, Managing Director of Lowter
Blog | American Swedish Institute | Save the Internet

Offline

 

#2 13 Aug 2009 17:30

lotrgamemast
Lowter Staff
From: England
Registered: 25 Jan 2005
Posts: 2484
Message  Website

Re: PHP Magic Getters and Setters

So if you had a variable in $object defined as:

Code:

$_publicData = Array(
    "some" => "data"
)

And you called:

Code:

$object->some;

You'd get "data" returned? Am I thinking about this right?

Offline

 

#3 13 Aug 2009 20:25

Ethan
Lowter Staff
From: Minneapolis, MN
Registered: 20 Jan 2005
Posts: 6960
Message  Website

Re: PHP Magic Getters and Setters

Yep, that's it.  Obviously, private and protected variables are done normally (although getters and setters for them individually might be worthwhile).

It may seem redundant, but it depends on how you handle exceptions.  You could call $object->doesNotExist and avoid having a fatal error called, but rather log it or something.  Plus, you'd be surprised how much trouble directly accessing class members can cause in larger applications with multiple developers.


Ethan, Managing Director of Lowter
Blog | American Swedish Institute | Save the Internet

Offline

 

#4 14 Aug 2009 18:27

Tom
Loco Lowter Member
From: UK
Registered: 25 Jan 2005
Posts: 2503
Message  Website

Re: PHP Magic Getters and Setters

I like this, it is such a pain when you have to make loads of get methods to access anything, just bloats your code (I feel anyway)


Meaning of life: we learn a bunch of stuff then we die.
http://www.thehardcorelife.com
http://blog.thehardcorelife.com

Offline

 

Board footer

Powered by PunBB
© Copyright 2002–2005 Rickard Andersson