php 修飾符和魔術方法 (基礎)

晴了發表於2019-02-16

PHP中有三種訪問修飾符,它們可以分別用在類的屬性和方法上(類的屬性和方法統稱為類的成員),用來修飾類成員的訪問許可權

  • public(公共的、預設)
  • protected(受保護的)
  • private(私有的)

php 常用魔術方法:

__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __invoke(), __clone() 

在下面的例子中展示一下用法

class Test
{
    private $a = `a`;
    protected $b = `b`;
    public $c = `c`;

    public function __set($name, $value)
    {
        // TODO: Implement __set() method.
    }

    public function __get($name)
    {
        // TODO: Implement __get() method.
    }

    public function __construct()
    {
        echo `begin construct!`;
    }

    public function __destruct()
    {
        echo `begin destruct!`;
    }

    public function __invoke()
    {
        echo `try to invoke!`;
        // TODO: Implement __invoke() method.
    }

    public function __isset($name)
    {
        // TODO: Implement __isset() method.
    }

    private function get1()
    {
        var_dump(`private get a :` . $this->a . "
");
        var_dump(`private get b :` . $this->b . "
");
        var_dump(`private get c :` . $this->c . "
");
    }

    protected function get2()
    {
        var_dump(`protected get a :` . $this->a . "
");
        var_dump(`protected get b :` . $this->b . "
");
        var_dump(`protected get c :` . $this->c . "
");
    }

    public function get3()
    {
        var_dump(`public get a :` . $this->a . "
");
        var_dump(`public get b :` . $this->b . "
");
        var_dump(`public get c :` . $this->c . "
");
    }

}

呼叫Test方法
$t = new Test();
$t(123); // 呼叫invoke

$t->get3();
// public 方法可以將所有變數都能被呼叫到
// public get a :a
// public get b :b
// public get c :c

// __set 和 __get 魔術方法使用,如果不定義,那麼對於 private 屬性 $a 將無法被操作
//$t->a = `123`;
//echo $t->a;

//$t->get1(); // private 方法外部不可被呼叫
//$t->get2(); // protected 方法外部不可被呼叫


class Test2 extends Test
{
//    private $b = ``; // 報錯,子類繼承修飾符等級不能低於父類
    protected $b;// ok 或  public $b
    private function get1()
    {
        var_dump(`Test2 private get a :` . $this->a . "
"); // 報錯,私有變數不能被繼承
        var_dump(`Test2 private get b :` . $this->b . "
");
        var_dump(`Test2 private get c :` . $this->c . "
");
    }

    public function get2() // 繼承時修改了 訪問許可權
    {
//        var_dump(`get a :` . $this->a . "
");// 報錯,私有變數不能被繼承
        var_dump(`Test2 public get b :` . $this->b . "
");
        var_dump(`Test2 public get c :` . $this->c . "
");
    }

    public function get3()
    {
//        var_dump(`get a :` . $this->a . "
");// 報錯,私有變數不能被繼承
        var_dump(`Test2 public get b :` . $this->b . "
");
        var_dump(`Test2 public get c :` . $this->c . "
");
    }
}

$t2 = new Test2();
$t2->get3();
$t2->get2(); // protected方法外部無法被呼叫,但修改為public後可以被使用
//$t2->get1(); // private方法外部無法被呼叫

相關文章