Public, Private & Protected in PHP 5

-

Introduction

Public, Private and Protected are access identifiers that allow you to specify what level of access other code has to certain variables and methods within an individual class.

Some data you may want to keep within a class and other data available to a whole program – Public, Private and Protected identifiers allow us to control the scope of our data.

The Public Identifier

When using the pubic identifier you are allowing access to a classes attributes and methods from outside the class e.g. :

You can see the public identifier stated before the attributes and before the method. The following code would allow you to access the attributes:

The Private Identifier

When using the private identifier you are not allowing access to a classes attributes and methods from outside the class e.g. :

You can see the private identifier stated before the attributes and before the method. Trying to access the private variables like this:

would throw and error because the attribute is set to private. To access the attributes the class would have to have a public method that can return the value:

As you can see there is now an extra method that is public therefore this can be used to return the value because its within the correct scope:

The Protected Identifier

Now the protected identifier is used when dealing with inheritance. An attribute that is given a protected scope can only be accessed within the class and to any other classes that extend the base class. For example take our base class:

If you tried to access the ‘name’ after instantiating the Web_Developer object like below:

You would get an error because the attribute is not accessible from outside the class. But using the public method like so:

is ok, the main difference between protected and private class properties is that protected properties can also be accessed by extended classes.

Comments

Visitor stats.