标签:style blog color io 使用 ar strong art div
先贴出一张,直观的、估计大家都见过的关于public、protect、private的范围图
作用域
|
当前类
|
同一package
|
子孙类 |
其他package
|
public
|
T
|
T
|
T
|
T
|
protect
|
T
|
T
|
T
|
F
|
private
|
T
|
F
|
F
|
F
|
T : true F : false
1 <?php 2 class test { 3 private $variable = 1; 4 public function setVal($param) { 5 $this->variable = $param; 6 } 7 public function getVal() { 8 return $this->variable; 9 } 10 private function output() { 11 echo 1; 12 } 13 } 14 class test2 extends test { 15 public function __construct(){ 16 $this->variable =2; 17 } 18 } 19 $obj = new test2(); 20 print_r($obj); 21 echo ‘<br />‘; 22 echo $obj->variable; 23 //$obj->output(); 24 echo ‘<br />‘; 25 echo $obj->getVal(); 26 echo ‘<br />‘; 27 $obj->setVal(3); 28 echo $obj->getVal(); 29 echo ‘<br />‘; 30 print_r($obj); 31 } 32 ?>
输出:
test2 Object ( [variable:test:private] => 1 [variable] => 2 )
2
1
3
test2 Object ( [variable:test:private] => 3 [variable] => 2 )
1 <?php 2 class test { 3 private $variable = 1; 4 public function setVal($param) { 5 $this->variable = $param; 6 } 7 public function getVal() { 8 return $this->variable; 9 } 10 private function output() { 11 echo 1; 12 } 13 } 14 class test2 extends test { 15 public function __construct(){ 16 //$this->variable =2; 17 private $variable = 2; 18 } 19 } 20 $obj = new test2(); 21 print_r($obj); 22 echo ‘<br />‘; 23 echo $obj->variable; 24 //$obj->output(); 25 echo ‘<br />‘; 26 echo $obj->getVal(); 27 echo ‘<br />‘; 28 $obj->setVal(3); 29 echo $obj->getVal(); 30 echo ‘<br />‘; 31 print_r($obj); 32 ?>
<?php class test { private $variable = 1; public function setVal($param) { $this->variable = $param; } public function getVal() { return $this->variable; } private function output() { echo 1; } } class test2 extends test { public function __construct(){ $this->variable =2; } } $obj = new test2(); print_r($obj); $obj->setVal(3); echo $obj->getVal(); echo ‘<br />‘; print_r($obj); } ?>
上班零时整理,结果还华丽丽的被领导看到了,尴尬死我了,格式没太顾得上,哎、、、、
public、protect、private在父类子类中使用
标签:style blog color io 使用 ar strong art div
原文地址:http://www.cnblogs.com/wxb0328/p/3972395.html