kuzey beytar
kuzey beytar

Reputation: 3226

Is visibility in PHP classes important, and why?

As you know, PHP class has private, public and protected keywords. I just started to write classes and I wonder what are the advantages of class visibility in PHP5.

And of course also disadvantages...

Upvotes: 6

Views: 1991

Answers (5)

webbiedave
webbiedave

Reputation: 48887

Let me answer with an example:

Leaving it all up to the client (not good):

class myClass
{
    public $name; // cannot contain spaces

}

$mc = new myClass();
$mc->name = 'John Smith'; // Oh no!

Now with more control:

class myClass
{
    private $name; // cannot contain spaces

    public function setName($value)
    {
        if (strpos($value, ' ') !== false) {
            throw new Exception('Name contains space.');
        }

        $this->name = $value;
    }

    public function getName()
    {
        return $this->name;
    }

}

$mc = new myClass();
try {
    $mc->setName('John Smith');
} catch (Exception $e) {
    echo 'Cannot set name. Reason: ', $e->getMessage();
}

Using access specifiers allows you to better protect members/methods from bad use. There are no disadvantages other than something more to learn.

Upvotes: 4

Felix Kling
Felix Kling

Reputation: 817218

It is useful if you want to apply OOP practices such as Information Hiding(Encapsulation).

If you declare class members as private, they cannot be accessed from code outside of your class. You have to provide methods to access them. This separates the interface of your class from the actual implementation.
Other code that uses your class does not need to know the name of the class member or how you actually store information internally.

Example:

Consider a class Books the somehow gives me a list of books. I can define a public member that holds an array of books:

class Books {
    public $list;
}

On the other side, if I define a method getList(), I can change the implementation later, without effecting the code that uses the class:

class Books {
    private $list;
    public function getList() {
         // get list from database, from XML, etc.
         // might use $list internally but does not have to
    }
}

Obviously, you don't need modifiers like private, protected or public to implement this behavior, but it leads to better structured code and clearer interfaces. Imagine you have a class that has both a public $list and a method getList(). How do you know which one of them to use?
This applies not only for getting values, but especially for setting values.

There are no disadvantages if you use them, only advantages IMHO. The difference between them is the scope of the visibility. public members can be accessed from outside code, protected members can be accessed form inheriting classes and private members only from the class.

Methods can also have these modifiers and follow a similar purpose. E.g. if a method is declared as private, it is clear that it is probably some kind of helper method, that is used internally only and is not supposed to be called form the outside.


So in the end it boils down to two things:

  • Control: Which parts of your class can be accessed in which way
  • Self-documentation or understanding: Other people using your class can figure out more easily, which part of your class they are supposed to access and which not.

Upvotes: 10

Crozin
Crozin

Reputation: 44406

Just imagine what would happen if you have full access to the electrical installation in your home. How long it would take before you would burn down the building or kill yourself?

Internal processes might be dangerous that's why that installation provides some public interface. In this example it would be a socket and a light switch. It's quite hard to burn down the house using light switch, isn't it?

Upvotes: 1

jwueller
jwueller

Reputation: 30991

Visibility is one of the main ideas behind encapsulation, which powers object-oriented programming (esp. proper polymorphism). You should definitely specify the visibility properly, since you cannot guarantee that your class will work as expected, otherwise. By using this correctly, you have exact control over how your class members can be accessed.

I do not know of any disadvantages (except that you need to write some extra lines of code).

Upvotes: 3

simshaun
simshaun

Reputation: 21476

Yes they are important. Put simply, they keep your code from accessing things in the wrong places.

I'm not sure of any disadvantages, other than declaring something protected or private may mean a little more work writing a getter and a setter method.

Upvotes: 0

Related Questions