Jump to content

What Problems Does Direct Access To $This->Xxx Cause


davidannis

Recommended Posts

I have read on this site that directly accessing a variable in my class can cause problems. For example the oop tutorial says:

For example: with the property $name (in object $stefan) you could get its value like so:

 

$name = $stefan->name;

 

Though doable, it is considered bad practice to do it because it can lead to trouble down the road. You should use getter methods instead - more on that later.

 

or in this thread

 

Keep in mind, there's little point in using the getters from within the object, so you may as well just use "$this->firstname" rather than "$this->get_firstname()" and make it slightly easier on PHP. The getters are there to access your object's properties from "outside" the object, so you can control how they are accessed or used.

 

My question is, what problems am I avoiding by creating setter classes? I have a class I'm working on now that just seems bloated by all the getter and setter methods.

Link to comment
Share on other sites

The only problem I could probably see is if you are writing something that might conflict with queries or other predefined statements and maybe a person might get it confused with another class that is not extended with extends?

 

Come to think of it I really can't think of a time that I wrote something like that within public, protected or private function and I can't think of reason why to?

 

And I don't know why you would be using a lot of getter or setter classes/methods?

Edited by Strider
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...