Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 586
kuzey beytar Avatar asked Nov 24 '10 15:11

kuzey beytar


People also ask

What is the importance of class visibility in OOP PHP?

Visibility is declared using a visibility keyword to declare what level of visibility a property or method has. The three levels define whether a property or method can be accessed outside of the class, and in classes that extend the class.

What is visibility mode in PHP?

PHP has three visibility keywords - public, private and protected. A class member declared with public keyword is accessible from anywhare. A protected member is accessible from within its class and by inheriting class.

What do you mean by visibility of a class?

Visibility of a class member (property, method or constant) is where it can be accessed. ( Eg: inside the class, outside the class) Properties, methods, and constants can be declared with visibility.

What is the default visibility in PHP?

Default is public. Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.


3 Answers

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.
like image 182
Felix Kling Avatar answered Oct 21 '22 00:10

Felix Kling


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).

like image 25
jwueller Avatar answered Oct 21 '22 00:10

jwueller


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.

like image 36
webbiedave Avatar answered Oct 21 '22 01:10

webbiedave