PHP implements the method of accessing its private attribute private and its protection attribute protected outside the object
- 2021-08-16 23:27:10
- OfStack
This article illustrates how PHP can access its private attribute private and its protected attribute protected outside of an object. Share it for your reference, as follows:
public represents global access rights, which can be accessed by internal and external subclasses of the class;
private denotes private access rights, which can only be used inside this class;
protected denotes protected access rights that can be accessed only in this class or subclass or parent class;
Examples of more classic usage are as follows:
<?php
// Parent class
class father{
public function a(){
echo "function a<br/>";
}
private function b(){
echo "function b<br/>";
}
protected function c(){
echo "function c<br/>";
}
}
// Subclass
class child extends father{
function d(){
parent::a();// Call the parent class's a Method
}
function e(){
parent::c(); // Call the parent class's c Method
}
function f(){
parent::b(); // Call the parent class's b Method
}
}
$father=new father();
$father->a();
// $father->b(); // Display error Private methods cannot be called externally Call to protected method father::b()
// $father->c(); // Display error Protected methods cannot be called externally Call to private method father::c()
$chlid=new child();
$chlid->d();
$chlid->e();
// $chlid->f();// Display error Unable to call parent class private Method of Call to private method father::b()
?>
Run results:
function a
function a
function c
Outside objects, php accesses private and protected properties as follows:
class yunke
{
protected $a = 55;
private $b = 66;
public function merge()
{
$result = clone $this;
$result->a=88;
$result->b=99;
return $result;
}
public function show()
{
echo $this->a;
echo $this->b;
}
}
$test = new yunke;
$test->show();
$test2=$test->merge();
$test2->show();
Output:
55668899
For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"
I hope this article is helpful to everyone's PHP programming.