free tutorials logo spacer
spacer
PHP
 
     
   
shaddow bottom left

Public, Private and protected, Access control, Who can use what

What you have learned in the past 5 sections should allow you to use object oriented programming, you can do many things with objects, and you can use all your previous procedural skills with OO, but if you do this early, things will probably get a bit messy.

In this part of the tutorial, i will be showing you how to restrict or relax access to methods and properties by means of 3 magic keywords.

Earlier i declared methods and properties as PUBLIC and told you this is how we do it, so you simply added the keyword public, in PHP4, the word public used to be added implicitly (We used the VAR keyword instead), and if you omit it in PHP5, it will also be added implicitly, but with PHP5 it is better to go explicit since we have 2 more keywords to replace public, they are, Private, and Protected

Access Who can access
Public It is like a global variable, Anyone can access it from anywhere in your code, We just write $camry->price and it will print the price
Private Only from within the enclosing class, this one is most restrictive
Protected From within the enclosing class and from subclasses using parent::

So, what is in this for me you may ask ?
To begin with, when you write fine code, most properties will be protected, then as your program evolves, you can relax this restiction for some if it is absolutly necessary, and you should tighten the restrictions (With private) whenever possible, Otherwise the class should have methods to alter, read, and deal with the property, So a public method (Function) within the class deals with protected and private entries.

You may also ask, why not start private for all properties and then relax as necessary, maybe it is a good idea, but i usually start with protected, It is my idea of a balance between saving time and writing good code, either way, do not start PUBLIC !

 



Your Name:

Subject:

Your Comment: