Skip to content
Advertisement

OO PHP direct member access [closed]

I always thought you should never set/get a member variable directly. E.g.

$x = new TestClass();
$x->varA = "test":
echo $->varB;

I thought you should always use object methods to access member variables.

But I’ve just been looking at __set and __get, which imply it’s ok to access members directly.

Advertisement

Answer

There’s no right answer here.

In the beginning, direct access to member variables was considered a bad idea because you lose the ability to make that access conditional upon some set of arbitrary programming logic. That’s why we have the terror of getter and setter methods.

Having magic methods like __set and __get removes this concern. You can have users of your object access member variables all you want and then if you discover you need some programatic logic around that access, you can use the magic methods.

However, particularly in PHP, __set and __get aren’t free from a performance perspective. Also, remember that __set and __get are only invoked when an inaccessible (private, protected, etc.) member variable is accessed. This means there’s no way to invoke __set and __get from within a class, outside of removing the member variable from the class definition, which makes your class less clear.

Like most things PHP, there’s no clear “best” way to handle this.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement