Updated March 20, 2023
Introduction to Private in PHP
Keywords are the words used as a reserve in a program that has a special meaning assigned to them. They can be a command or parameter. Like every other programming language, PHP also has a set of special words called keywords which cannot be used as variable names for other purposes. They are also called as reserved names.
A private keyword, as the name suggests is the one that can only be accessed from within the class in which it is defined. All the keywords are by default under the public category unless they are specified as private or protected. Private keywords help in security purposes by giving the least visibility to the keyword in the entire code. It is also easier to refractor when there is only a single class calling this keyword.
Apart from private keywords, there can also be private methods too. In object-oriented programming, methods are the set of procedures associated with any class. In the case of private methods, they are allowed to be called only within methods belonging to the same class or its module.
There are also private constants and properties which can be declared. The visibility in these cases is limited only between their classes and not instances. If the two objects are of the same type then one object can call another object’s private method.
Syntax:
Any variable, property or a method can be declared private by prefixing it with a “private” keyword.
class MyClass()
{
private variable_name;
private Method_name();
private $priv = 'Private property';
}
Example of Private Property
Let us understand the working of private property in PHP by taking the below example:
Code:
<?php
/**
* Definition of PHPExample
*/
class PHPExample
{
public $public = 'Public property';
protected $protected = 'Protected property';
private $private = 'Private property';
function displayValue()
{
echo $this->public;
echo "\n";
echo $this->protected;
echo "\n";
echo $this->private;
echo "\n";
}
}
$val = new PHPExample();
echo $val->public; // Public will work without any error
echo "\n";
echo $val->protected; // Uncaught Error: Cannot access protected property PHPExample::$protected in /workspace/Main.php:21
echo $val->private; // Uncaught Error: Cannot access private property PHPExample::$private in /workspace/Main.php:22
$val->displayValue(); // Displays all 3 Public, Protected and Private properties
/**
* Definition of PHPExample2
*/
class PHPExample2 extends PHPExample
{
// It supports redeclaration of public and protected properties and not private
public $public = 'Public2 property';
protected $protected = 'Protected2 property';
function displayValue()
{
echo $this->public;
echo "\n";
echo $this->protected;
echo "\n";
echo $this->private; //Undefined property: PHPExample2::$private in /workspace/Main.php on line 39
}
}
$val2 = new PHPExample2();
echo $val2->public; // Public will work without error
echo "\n";
echo $val2->protected; // Fatal Error
echo $val2->private; // Undefined property: PHPExample2::$private in /workspace/Main.php on line 46
$val2->displayValue(); // Shows Public2, Protected2, Undefined
?>
Output 1:
Output 2: After commenting on line 23.
Output 3: After commenting on line 24.
Output 4: After commenting on lines 46, 47 and 40.
Explanation to the above code: When you run this code entirely, you are bound to get fatal errors at a few line numbers like the line:25,26,45,52,53. We are first declaring all 3 properties public, private and protected in the main class PHPExample to display their respective words. Inline 25, we are trying to access all 3 properties from the PHPExample class. Since private and protected examples cannot be accessible outside their class, we get a fatal error in the output as shown and only public property is displayed.
In the second half of the code, we are declaring another class PHPExample2 where we are re-declaring the display values for protected and public properties. The same is not allowed for private and then we are performing the same action as in the first half. Since we are trying to call private property which is not declared here, we get undefined property error.
Example of Private Method and Keyword
Let us understand the working of the private method and keywords in PHP by taking the below example:
Code:
<?php
class NameExample {
// Declaring first name as private value
private $first_name;
// Declaring last name as private value
private $last_name;
public $public = 'Displaying from public method';
private $private ='Displaying from private method';
// private function for setting the value for first_name
private function fName($first_name) {
$this->$first_name = $first_name;
echo $this -> private;
}
// public function for setting the value for last_name
public function lName($last_name) {
$this->$last_name = $last_name;
echo $this -> public;
}
// public function to display full name value
public function dispName() {
echo "My name is: " . $this->$first_name . " " . $this->$last_name;
}
}
// Creating a new object named $arun of the class
$arun = new NameExample();
// trying to access private class variables
$arun->$first_name = "Arun"; // invalid
$arun->$last_name = "Sharma"; // invalid
// calling the public function to set $first_name and $last_name
$john->fName("John");
$arun->lName("Wick");
// $arun-> dispName();
?>
Output 1:
Output 2: After commenting lines 32, 33 and 36.
Explanation to the above code: In the above example, $first_name and $last_name are declared as private variables of class NameExample and therefore they cannot be directly called using a class object. Hence when we first try to run the code we get an error as “Undefined variable: first_name in /workspace/NameExample.php on line 32” and the same goes for line 33. When we comment on these 2 lines and run the code again we get the error “Uncaught Error: Call to a member function name() on null in /workspace/NameExample.php:36”.
This is because we have declared function fName as private and it is trying to access the same. The code runs smoothly when line 36 is also commented and displays from method name since it is a public method.
Advantages of Using Private in PHP
Below are the Advantages of Using Private in PHP:
- Private variables can be still accessed by the use of “getters” and “setters” which gives the coder more control over accessing the data.
- Private inturn means encapsulation which also separates the variables from one class to another hence protects the changes made to the class internally.
- The behavior of private variables is restricted inside that particular class and also avoids confusion.
- Private variables can easily be re-implemented without the risk of breaking the code anywhere.
Rules and Regulations for Private in PHP
Following are the Rules and Regulations to be followed for Private in PHP:
- For any variable member or a method, one must always declare its scope as to whether it belongs to public, protected or private.
- In the order of methods one should follow the following order: public,> protected > private
- Private variables cannot be accessed from the subclass declared by extending them from the main class in which they are declared. However, it can be accessed if the same private property is again declared in the subclass but it is not advisable to do so.
- Hence a private method declared in a class can be called only inside of that class.
Conclusion
Private is a way of restricting the accessibility of variables, methods or properties of a class. They can only be accessed in the class they are declared and not from any subclass which extends from it. Any protected property from a parent class can be overridden by a subclass and made public but cannot be made as private.
Recommended Articles
This is a guide to Private in PHP. Here we discuss two different examples of Private in PHP with advantages and rules and regulations to be followed in it. You can also go through our other related articles to learn more –