How to directly access the private attribute in the php instance object

  • 2021-08-10 06:59:37
  • OfStack

Preface

This article focuses on how to directly access private properties in an php instance object. Before introducing the key parts, we will review the object-oriented access control of php under 1.

Access control to a property or method is achieved by prefacing the keywords public (public), protected (protected), or private (private). Class members defined as public can be accessed anywhere. Class members defined as protected can be accessed by themselves, their children and parents. Class members defined as private can only be accessed by the class in which they are defined.

Class attributes must be defined as public, protected and private. If defined by var, it is considered public.

See the following sample code (from the official document: 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 property of a class, we throw a fatal error.

Here's what the article title does, accessing the private properties of the php instance object.

In our normal practice, 1 is usually to write an public method and return this property.


public function getPrivate()
{
 return $this->private;
}

The fact is that we should have done this.

The following is just the use of special scenes. I hope everyone will not behave in such a way when writing code at ordinary times.


<?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 new a new A object, and then assign a value to the private attribute a of this instance, but there is no error!

Explanation: Because objects of the same class can access each other's private and protected members even if they are not instances of the same class. This is because the details of the concrete implementation inside these objects are known.

Summarize


Related articles: