时间:2021-07-01 10:21:17 帮助过:21人阅读
<?php
/**
* Define MyClass
*/
class MyClass{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello(){
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; //Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
/**
* Define MyClass2
*/
class MyClass2 extends MyClass{
//We can redeclare the public and protected method, but not private
protected $protected = 'Protected2';
function printHello(){
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj->public; //Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, not Private
?>
代码片段
代码如下:
<?php
/**
* Define MyClass
*/
class MyClass{
// Contructors must be public
public function __construct() { }
// Declare a public method
public function MyPublic() { }
// Declare a protected method
protected function MyProtected() { }
// Declare a private method
private function MyPrivate() { }
// This is public
function Foo() {
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}
$myclass = new MyClass;
$myclass->MyPublic(); //Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work
/**
* Define MyClass2
*/
class MyClass2 extends MyClass{
// This is public
function Foo2(){
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); // Fatal Error
}
}
$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private
?>
另外在子类覆盖父类的方法时也要注意一点,子类中方法的访问权限一定不能低于父类
被覆盖方法的访问权限,也就是一定要高于或等于父类方法的访问权限。
例如,如果父类方法的访问权限是protected 那么子类中要覆盖的权限就要是protected
和public,如果父类的方法是public 那么子类中要覆盖的方法只能也是public,总之子类中的
方法总是要高于或等于父类被覆盖方法的访问权限。