This article mainly introduces you to the relevant information on how to directly access the private attributes in the PHP instance object. The article introduces it in detail through the example code. It has certain reference learning value for everyone's study or work. Friends in need Let’s learn together with the editor below.
Preface
This article mainly introduces the relevant content on how to directly access the private attributes in the PHP instance object. Before introducing the key parts, we Let’s first review PHP object-oriented access control.
Access control of properties or methods is achieved by adding the keywords public (public), protected (protected) or private (private) in front. Class members defined as public can be accessed from anywhere. A class member defined as protected can be accessed by itself, its subclasses, and its parent class. Class members defined as private can only be accessed by the class in which they are defined.
Class attributes must be defined as one of public, protected, and private. If defined with var, it is considered public.
Please see the sample code below (from official documentation: http://php.net/manual/en/language.oop5.visibility.php
<?php /** * Define MyClass */ class MyClass { public $public = 'Public'; protected $protected = 'Protected'; private $private = 'Private'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; } } $obj = new MyClass(); echo $obj->public; // Works echo $obj->protected; // Fatal Error echo $obj->private; // Fatal Error $obj->printHello(); // Shows Public, Protected and Private
As shown in the above code, when we use an instance object of a class to access a private or protected member attribute of a class, a fatal error will be thrown
##The following is the title of the article. What we need to do is access the private properties of the php instance object.
##According to our normal practice, we usually write a public method and then return this property ##.
public function getPrivate() { return $this->private; }
The fact is that we should do this.
<?php class A { private $a = 'self'; public function test() { $other = new self(); $other->a = 'other'; var_dump($other->a); } } $aa = new A(); $aa->test();
As shown in the above code, we created a new A object and assigned a value to the private attribute a of this instance. No error was reported!
Explanation:
##Summarize
The above is the detailed content of How to directly access private attributes in PHP instance objects?. For more information, please follow other related articles on the PHP Chinese website!