public、private和protected称为访问修饰符。与C++一样, PHP也具有三个访问修饰符, 例如public, private和protected。属性, 方法或常量的可见性可以通过在声明的前面加上这些关键字来定义。
- 如果类成员声明为public, 则可以在任何地方访问它。
- 如果将类成员声明为protected, 则只能在类本身内部以及通过继承和父类访问它。
- 如果类成员声明为private, 那么只有定义该成员的类才能访问它。
public访问修饰符:
该修饰符可以在类的内部和外部使用。
例子:
<?php
//BaseClass
class pub {
public $tag_line = "A Computer Science Portal for Geeks!" ;
function display() {
echo $this ->tag_line. "<br/>" ;
}
}
//SubClass
class child extends pub {
function show(){
echo $this ->tag_line;
}
}
//Object Declaration
$obj = new child;
//A Computer Science Portal for Geeks!
echo $obj ->tag_line. "<br/>" ;
//A Computer Science Portal for Geeks!
$obj ->display();
//A Computer Science Portal for Geeks!
$obj ->show();
?>
输出如下:
A Computer Science Portal for Geeks! A Computer Science Portal for Geeks! A Computer Science Portal for Geeks!
protected访问修饰符:该修饰符可以在定义它的类及其父类或继承的类中使用。
例子:
<?php
//Base Class
class pro {
protected $x = 500;
protected $y = 500;
//Subtraction Function
function sub()
{
echo $sum = $this ->x- $this ->y . "<br/>" ;
}
}
//SubClass - Inherited Class
class child extends pro {
function mul() //Multiply Function
{
echo $sub = $this ->x* $this ->y;
}
}
$obj = new child;
$obj ->sub();
$obj ->mul();
?>
输出如下:
0 250000
private访问修饰符:该修饰符可以在定义它的类中使用。 (无法在继承的类中的类外部访问)。
例子:
<?php
//Base Class
class demo {
private $name = "A Computer Science Portal for Geeks!" ;
private function show()
{
echo "This is private method of base class" ;
}
}
//Sub Class
class child extends demo {
function display()
{
echo $this ->name;
}
}
//Object Declaration
$obj = new child;
//Uncaught Error: Call to private method demo::show()
$obj ->show();
//Undefined property: child::$name
$obj ->display();
?>
输出如下:
It will display error because private class data can not be accessed outside the class
其他示例:
例子:
<?php
class BaseClass
{
public $public = 'Public' ;
protected $protected = 'Protected' ;
private $private = 'Private' ;
function Display()
{
echo $this -> public ;
echo $this -> protected ;
echo $this -> private ;
}
}
$obj = new BaseClass();
echo $obj -> public ;
echo $obj -> protected ; //Cannot access protected property
echo $obj -> private ; //Cannot access private property
$obj ->Display(); //Displays all properties
class SubClass extends BaseClass
{
public $public = 'Public Sub Class' ;
protected $protected = 'Protected Sub Class' ;
function Display()
{
echo $this -> public ;
echo $this -> protected ;
echo $this -> private ;
}
}
$obj2 = new SubClass();
echo $obj2 -> public ;
echo $obj2 -> protected ; //Cannot access protected property
echo $obj2 -> private ; //Cannot access priavte property
$obj2 ->Display(); //Displays all properties
?>
输出如下:
It will display error because private class data can not be accessed outside the class
评论前必须登录!
注册