Jump to content
Lizard Wizard Coding Club

Access Private Member Through Public Function


Recommended Posts

I was experimenting with the access modifiers in Step 17 of Object Oriented PHP for Beginners. I made pinn_number a private property. I used the classes' constructor to set its value. Finally, I created a public function called get_pinn_number().

 

Outside of the class, I was able to obtain the value of pinn_number using get_pinn_number. I do not understand why this would work. I understand that the value of making properties private is so that their values are available only within the class where they are defined. Therefore, in practice, why would a developer make the value of a private property available through a public function? In practice, would a developer make get_pinn_number() a private function - and not a public one? This documentation is awesome! Thanks so much!

Link to post
Share on other sites
Therefore, in practice, why would a developer make the value of a private property available through a public function?

Because they need to access that property? I don't see a reason why this would be bad -- it's considered a best practice to keep a class' variables private, so they can't be accessed/changed directly, and instead access or change them via the class methods.

 

As far as I understand it, if you made get_pinn_number() a private function, it would only be accessible to functions within the class, and the developer wouldn't be able to access the pinn_number variable at all from outside the class.

Link to post
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...