There is an object of a certain class "A", you need to display its property and call a method.

php gives the error that there is no access to these methods. they are pretected.

how to get access?

  • More details:

There is an event

function before($obj) { } 

the $obj parameter is an object of the Events class that has a result (array) field - protected .

need to access it in the event. I'm trying to inherit:

 class myClass extends Events { public function A() { print_r($this->result); } } $q = new myClass; $q->A(); 

Naturally displays an empty result, since I refer directly to the class property not to the property of the object. How to address the object?

  • You are doing something wrong. Because the protectors are also available to the heirs too .... it would be better if you showed another code of the Events class and explained how and where before - Alexey Shimansky

2 answers 2

First of all , what you are doing is wrong. Protected properties should be used only in the current class or in its heirs. These are the basics of the PLO and must be reckoned with. It is better to think carefully, almost certainly there is another way to solve the problem.

Secondly , inheritance in this case will not help you because the object passed in before already created and is an instance of Events , and not of your child class myClass .

Thirdly , I will tell you about a small PHP extension that few people know about (or people just forget about its existence), namely the Reflection API . This extension allows you to work wonders. For example, you can get the values ​​of a protected property as follows:

 function before($obj) { $ref = new \ReflectionClass($obj); $prop = $ref->getProperty('result'); $prop->setAccessible(true); // А теперь немного магии. Переменная $res после выполнения строчки ниже будет содержать // значение защищенного свойства. $res = $prop->getValue($obj); } 

The same trick works for private properties.

    I see 2 ways:

     class Events { protected $result = array(0, 1, 2); public function getResult() { return $this->result; } } class myClass extends Events { public function A() { print_r($this->getResult()); } public function B() { print_r($this->result); } } $q = new myClass; $q->A(); $q->B(); 

    I do not see the complexity ... Or did I misunderstand the question?