Home » Php » How to make __get() called recursively in PHP?

How to make __get() called recursively in PHP?

Posted by: admin February 25, 2020 Leave a comment

Questions:

How to let C::update2() could access $this->a by __get()? I’m using PHP 7.

<?php

class C
{
        public $data = [];

        public function __get($p)
        {
                if (!array_key_exists($p, $this->data))
                        $this->update(); // should be a properties to update method mapper
                return $this->data[$p] ?? null;
        }

        public function update()
        {
                $api_data = ['a'=>'123','b'=>'456'];
                $this->data['a'] = $api_data['a'];
                if ($api_data['b'] == '456') {
                        $this->update2(); // in this method, it'll call some others API
                } else {
                        $this->update3(); // also calls API, but different from update2
                }
        }

        public function update2()
        {   
                echo json_encode($this->data)."\n";
                echo $this->a;
        }   

        public function update3()
        {   
                echo json_encode($this->data)."\n";
                echo $this->a;
                echo $this->b;
        }   
}

$c = new C;
echo $c->a;

output

{"a":"123"}
PHP Notice:  Undefined property: C::$a in /test.php on line 27
PHP Stack trace:
PHP   1. {main}() /test.php:0
PHP   2. C->__get() /test.php:32
PHP   3. C->update() /test.php:9
PHP   4. C->update2() /test.php:18
123

The reason I want to do this is I want to make it resolving the properties lazily and without knowing how the properties comes out(black box).

How to&Answers: