php class 访问控制

属性(attribute ) 必须声明访问控制类型    

类型:

public 公用

protected 受保护的

private  私有的

public 类型的属性 可以在外部访问

 

protected 及private 的都不能从外部访问,例如:

 1 class MyClass{
 2 
 3     public $a = 12;
 4     protected  $b = 34;
 5     private $c = 56;
 6 
 7 
 8     public function show_attr(){
 9         echo $this->a;
10         echo $this->b;
11         echo $this->c;
12     }
13 }
14 
15 $obj_1= new MyClass();
16 $obj_1->show_attr();
17 
18 echo $obj_1->a;
19 echo $obj_1->b;
20 echo $obj_1->c;

 

 

16行输出:123456

18行输出:12

19行、20行会报错,提示不能访问。

 

class MyClass2 extends MyClass
{
  public $a = 120;//会覆盖父类的属性
  protected $b = 340;//会覆盖父类的属性
  private $c = 560;//私有的不会被继承 

  function printHello()
  {
      echo $this->a;
      echo $this->b;
      echo $this->c;
  }
}


$obj_2 = new MyClass2();
$obj_2->show_attr();//输出 12034056
echo "<br />";
$obj_2->printHello();//输出120340560

 

 

方法(method)

 

/**
 *  method 
 */
class MyClass3
{

  public $a = 1;
  protected $b = 2;
  private $c = 3;
  
  function __construct()
  {
    echo $this->a;
    echo "<br />";
    echo $this->b;
    echo "<br />";
    echo $this->c;
    echo "<br />";
    
  }

  public function ShowA()
  {
    echo "<br>".$this->a;
  }
  protected function ShowB()
  {
    echo "<br>".$this->b;

  }
  private function ShowC()
  {
    echo "<br>".$this->c;

  }

  public function run_method()
  {
    echo "method start";

    $this->ShowA();
    $this->ShowB();
    $this->ShowC();
    echo "method end";

  }


  protected function run_method1()
  {
    echo "method1 start";
    $this->ShowA();
    $this->ShowB();
    $this->ShowC();
    echo "method1 end";

  }

  private function run_method2(){
    echo "method2 start";

    $this->ShowA();
    $this->ShowB();
    $this->ShowC();
    echo "method2 end";

  }



}

$obj_3 = new MyClass3();//1 2 3

$obj_3->ShowA();//method start 1 2 3method end
$obj_3->run_method();//1 2 3
$obj_3->run_method1();//error
$obj_3->run_method2();//error

 

继承

class MyClass4 extends MyClass3
{
  public function run_extend()
  {
    echo "<hr >";
    $this->run_method();
    $this->run_method1();
    $this->run_method2();
  }
}


$obj_4 = new MyClass4();
$obj_4->run_extend();

 

输出:


method start
1
2
3method endmethod1 start
1
2
3method1 end

Fatal error: Call to private method MyClass3::run_method2() from context 'MyClass4' 

私有的方法也是无法继承的

 

posted @ 2018-06-14 15:35  为知  阅读(234)  评论(0编辑  收藏  举报