Home  >  Article  >  Backend Development  >  Access control (visibility) in php classes and objects

Access control (visibility) in php classes and objects

黄舟
黄舟Original
2017-07-02 10:47:331831browse


Classes and Objects > Access Control(Visibility)
Even if objects of the same class Not the same instance can access each other's private and protected members. This is because the internal implementation details of these objects are known.

Access private members of the same object type

<?phpclass Test{
    private $foo;    public function construct($foo)
    {
        $this->foo = $foo;
    }    private function bar()
    {
        echo &#39;Accessed the private method.&#39;;
    }    public function baz(Test $other)
    {
        // We can change the private property:
        $other->foo = &#39;hello&#39;;
        var_dump($other->foo);        // We can also call the private method:
        $other->bar();
    }
}$test = new Test(&#39;test&#39;);$test->baz(new Test(&#39;other&#39;));?>

//Discover: By passing in the instance object, external access to private methods and properties is achieved

Classes and Objects> Access Control (Visibility)
Objects of the same class can access each other's private and protected members even if they are not the same instance. This is because the internal implementation details of these objects are known.

Access private members of the same object type

<?phpclass Test{
    private $foo;    public function construct($foo)
    {
        $this->foo = $foo;
    }    private function bar()
    {
        echo &#39;Accessed the private method.&#39;;
    }    public function baz(Test $other)
    {
        // We can change the private property:
        $other->foo = &#39;hello&#39;;
        var_dump($other->foo);        // We can also call the private method:
        $other->bar();
    }
}$test = new Test(&#39;test&#39;);$test->baz(new Test(&#39;other&#39;));?>

//Discover: By passing in the instance object, external access to private methods and properties is achieved

The above is the detailed content of Access control (visibility) in php classes and objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn