Php without overload inside static function

I don't seem to understand why the code below prints "TEST" only twice.

<?php class A { private $test = "TEST<br />"; public static function getInstance() { return new self(); } public static function someStaticMethod() { $a = new self(); $a->test; } public function __get($args) { echo $this->$args; } } /* echo "TEST" */ $a = new A(); $a->test; /* echo "TEST" */ $a2 = A::getInstance(); $a2->test; /* No output... eeerhm... how come? Why is $a->test (inside someStaticMethod()) not being overloaded by __get ?? */ A::someStaticMethod(); ?> 

The PHP site says ( link ):

Property overloading only works in the context of an object. These magic methods will not be triggered in a static context. Therefore, these methods should not be declared static. Starting with PHP 5.3.0, a warning is issued if one of the overload magic methods is declared static.

But I think they are trying to say that u should declare magic methods static. eg:.

public static function __get () {}

Plus the fact that I actually use it in the context of an object. $ a = new self (); returns an instance of class A in the variable $ a. Then I use $ a-> test (object context imo?) To retrieve the private variable "test", which in turn must be overloaded ...

I'm confused...

+4
source share
2 answers

It seems that in the context of A:: someStaticMethod PHP allows you to directly access the private variable $test , so the magic method does not execute. If you are echo $a->test; from there, you will see that they are being addressed.

This is the expected behavior, according to the PHP Manual :

Objects of the same type will have access to every other private and protected member, even if they are not the same instances. This is due to the fact that specific implementation details are already known when inside these objects.

+2
source

From manual :

Overload methods are called when interacting with properties or methods that were not declared or not visible in the current area.

When you call the static method someStaticMethod() , the private $ test is visible in the current area, so the magic __get method is not called.

+3
source

Source: https://habr.com/ru/post/1432798/


All Articles