php访问控制

首先需要明白php中类和函数有三种访问控制,分别是public,protected和private。

三者的区别

这三者的区别是public可以在其子类父类,以及实例化的对象中访问到,protectded只能在其子类和父类中访问,实例化的对象中也无法访问,private要求更高,只能在自身类中访问,其他任何地方都无法访问!。

这里写图片描述

编辑器会直接提示你b和c是受保护和私有的,无法访问。

这里写图片描述

在子类中private依然无法访问。

其它对象的访问控制

同一个类的对象即使不是同一个实例也可以互相访问对方的私有与受保护成员。这是由于在这些对象的内部具体实现的细节都是已知的。即在一个类中可以获取相同类实例对象的private或者protected对象,it is awesome!

class Test{

private $foo;

public function __construct($foo)
{
    $this->foo = $foo;
}

private function bar()
{
    echo 'Accessed the private method.';
}

public function baz(Test $other)
{
    // We can change the private property:
    $other->foo = 'hello';
    var_dump($other->foo);

    // We can also call the private method:
    $other->bar();
}
}

$test = new Test('test');
$test->baz(new Test('other'));

输出:
string(5) “hello”
Accessed the private method。

static关键字

声明类属性或方法为静态,就可以不实例化类而直接访问。静态属性不能通过一个类已实例化的对象来访问(但静态方法可以)。

注意 thisself this可以看做类的实例,可以访问类中的非静态变量和方法,如 this>bself访,self:: a

静态变量仅在局部函数域中存在,但当程序执行离开此作用域时,其值并不丢失,在函数中变量使用static修饰时,每次调用函数该变量产生的变化会保存下来。

function t1(){
    static $h=1;
    $h++;
    print_r($h);
}
$t->t1();
$t->t1();
$t->t1();
输出2 3 4

猜你喜欢

转载自blog.csdn.net/github_38392025/article/details/78325232