search

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.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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:

Private in PHP

Output 2: After commenting on line 23.

Private in PHP

Output 3: After commenting on line 24.

Private in PHP

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

Private in PHP

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:

Private in PHP

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

Private in PHP

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.

The above is the detailed content of Private in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool