Home > Article > Backend Development > Access control (visibility) in php classes and objects
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 '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'));?>
//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 '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'));?>
//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!