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.
ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock TestsStart 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:
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.
The above is the detailed content of Private in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
