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

Access control (visibility) in php classes and objects

黄舟
Release: 2023-03-12 11:08:01
Original
1866 people have browsed it


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;));?>
Copy after login
Copy after login

//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;));?>
Copy after login
Copy after login

//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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template