EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Private in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » Private in PHP

private in php

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.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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';
}

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,694 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

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:

private in php - 1

Output 2: After commenting on line 23.

private in php - 2

Output 3: After commenting on line 24.

private in php - 3

Output 4: After commenting on lines 46, 47 and 40.

private in php - 4

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:

Method and Keyword 1

Output 2: After commenting lines 32, 33 and 36.

Method and Keyword

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:

  1. Private variables can be still accessed by the use of “getters” and “setters” which gives the coder more control over accessing the data.
  2. Private inturn means encapsulation which also separates the variables from one class to another hence protects the changes made to the class internally.
  3. The behavior of private variables is restricted inside that particular class and also avoids confusion.
  4. 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:

  1. For any variable member or a method, one must always declare its scope as to whether it belongs to public, protected or private.
  2. In the order of methods one should follow the following order: public,> protected > private
  3. 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.
  4. 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 –

  1. Functions in PHP
  2. PHP Form
  3. For Loop in PHP
  4. Protected in PHP

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

1 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More