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!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools