Public and Private in PHP-Access Modifiers in PHP OOPs

Spread the love

Public and Private in PHP

What are the access modifiers and what are there use?

We have already used “public” access modifier in our previous chapters in class properties and methods. In this tutorial, you will learn more about the Public and Private in PHP more specifically what are the access modifiers in PHP.

In this chapter, I will focus on “public” and “private” modifiers and in the chapter of Inheritance we will see another modifier i.e. “protected”.

What is Encapsulation:

Encapsulation is simply a concept of wrapping up a code like properties and method inside a class and giving access to them using methods with the help of access modifiers.

It means all the variables and functions required to write a program will be wrapped inside a code block which is nothing but a class and allowing access to them using methods.

Just like a medicine put inside a capsule covering it up, here code is put inside a class block and covered with the access modifiers like public, private and protected.

Let’s see in details about access modifiers.

Public and Private in PHP: What is access modifier?

As its name suggests access modifiers are those who can modify the access to properties and methods.

They allow or disallow which things can be accessed and which cannot or with specific permission outside the class.

What is public access modifier?

Let’s see public access modifier in public and private in PHP topic. Public access modifier allows the properties and methods to access outside the class.

As its name, after adding “public” keyword before the properties or methods, makes them public to the outside world of a class.


Let’s see an example.


<?php
class Mobile
{
    public $companyName;
    public $color = "Red";
    public $hasCamera= true;

    public function calling()
    {
        return "<br>Calling from a ". $this->companyName." mobile, with ".$this->color." color.";
    }
}

$iphone = new Mobile();

$iphone->companyName = "Apple";

echo "Company Name = ".$iphone->companyName;
echo "<br>Color = ".$iphone->color;
echo "<br>Camera = ".$iphone->hasCamera;

echo $iphone->calling();

?>



Output:


Company Name = Apple
Color = Red
Camera = 1
Calling from a Apple mobile, with Red color.

As you can see we have applied the public keyword to all the properties and method of a class.

Because of this, we are allowed to access them outside a class using the class object $iphone with the arrow operator.

Even if you don’t specify the public keyword in front of properties and method then also by default they will be public.

What is private access modifier?

Private access modifier works exactly opposite to the public. It restricts access to properties and methods within the class.

It means the properties and methods which are declared as private using the private keyword cannot be accessed outside a class.

Let’s see the same example, but at this time just change the public to private and try to access the same members of a class.

<?php
class Mobile
{
    private $companyName;
    private $color = "Red";
    private $hasCamera= true;

    private function calling()
    {
        return "<br>Calling from a ". $this->companyName." mobile, with ".$this->color." color.";
    }
}

$iphone = new Mobile();

$iphone->companyName = "Apple";

$iphone->color = "White";

$iphone->hasCamera= false;

echo "Company Name = ".$iphone->companyName;
echo "<br>Color = ".$iphone->color;
echo "<br>Camera = ".$iphone->hasCamera;

echo $iphone->calling();

?>

The output of the above program will show a Fatal error message that ” Cannot access private property”.

This happens because all the members of the class are made private and not available outside a class.

But what is the use of private if members are not accessible?

It ensures encapsulation or security.

Let’s say you have created an iphone object with a company name Apple.

Now if the companyName property is public and other people are also having “DIRECT” access to the class property companyName, then anybody can change the name of a company from “Apple” to “Samsung“, which would be wrong.

So you need to keep certain things in your product restricted from the outside world so that nobody can change them.

In this situation, “private” comes in picture. This will restrict the direct access of the properties and also functions/methods from outside of a class.

That’s why when you try to change the properties of $iphone object using statements


$iphone->companyName = “Apple”;
$iphone->color = “White”;
$iphone->hasCamera= false; 

from outside of a class you get a fatal error. Also, you are not able to access these properties outside of a class direct using echo statements.

Also, this is bad practice to set and access properties directly from outside a class.

But now another problem arises. How can we assign the properties values in a class and access then, even by keeping them private?

In this case setter and getter methods comes in picture.

What are the setter and getter methods?

Setter and getter are just simple methods defined as public.

As their name suggests, setter methods are used to set properties of a class by passing arguments to them.

And getter methods are used to get or access the properties of a class.

Let’s update the above program as follows.

<?php
class Mobile
{
    private $companyName;
    private $color = "Red";
    private $hasCamera= true;

    public function setCompanyName($name)
    {
        $this->companyName = $name;
    }

    public function getCompanyName()
    {
        return $this->companyName;
    }
}

$iphone = new Mobile();

$iphone->setCompanyName("Apple");

echo "The company name of an iPhone is = ".$iphone->getCompanyName();

?>

Now the output of the above program will be:


The company name of an iPhone is = Apple

As you see we have used a setter method name “setCompanyName” with a parameter “$name” and with “public” access specifier.

And after creating an object $iphone we have called it as $iphone->setCompanyName(“Apple”) from outside of a class.

Inside “setCompanyName” method, “companyName ” property is assinged a name “Apple“.

Also, we have used a getter method “getCompanyName” with “public” access specifier and returning a compnyName property.

Now you can only access the company name using a getter method getCompanyName() and not directly by property name.

Still, the question arises that though we are using a public setter method to set a property still other users are able to set properties using setter methods.

Yes, but now you can restrict them by adding certain authentication in setter method using simple “if” condition.

Let’s update the setCompanyName method by adding an if condition to check the username and password sent by iphone object.

Updating the above program.

<?php
class Mobile
{
    private $companyName;
    private $color = "Red";
    private $hasCamera= true;

    public function setCompanyName($name, $username, $password)
    {
        if($username == "john" && $password == "john123")
        {
            $this->companyName = $name;
        }
    }

    public function getCompanyName()
    {
        return $this->companyName;
    }

    public function calling()
    {
        return "<br>Calling from a ". $this->companyName." mobile, with ".$this->color." color.";
    }
}

$iphone = new Mobile();

$iphone->setCompanyName("Apple","john","john123");

echo "The company name of an iPhone is = ".$iphone->getCompanyName();

?>

Here I have updated the setCompanyName() method for receiving two more parameters username and password and added an if condition to check whether a username is “john” and password “john123” or not.

If both username and password are correct in if block then only you will be able to set the company name.

In this way, you can restrict the user with particular authority only to change or access the private properties or methods in a class. You can also add restriction to the access of a property in a getter method.

This was a very simple example of an if condition in a setter method and just for an explanation. You can create a separate login system with proper login functionality.

This process of wrapping of code inside a class with access modifiers comes under a concept of encapsulation, a feature in object oriented programming.

In this tutorial, we have seen Public and Private in PHP in detail.

We will see another access modifier “protected” in the next chapter Inheritance in details.


Spread the love

Leave a Comment