废码🐴

脑子不好使的时候,连写出来的代码都很魔性:P。

<?php
class Chain {
    private $data = [];
    private $value;

    public function __construct($v=null) {
        $this->value = $v;
    }

    public function __set($name, $value) {
        $obj = new self($value);
        return $this->data[$name] = $obj;
        return $obj;
    }

    public function __get($name) {
        if(array_key_exists($name, $this->data)){
            return $this->data[$name];
        } else {
            $obj = new self();
            $this->data[$name] = $obj;
            return $obj;
        }
    }

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

// set
$chain = new Chain();
$chain->a = 'hello a';
$chain->a->b = 'hello b';
$chain->a->b->c = 'hello c';
$chain->a->b->c->d->e->f = 'hello f';
// get 
var_dump($chain->a->b->c->value());
var_dump($chain->a->b->value());
var_dump($chain->a->b->c->d->value());
var_dump($chain->a->b->c->d->e->value());
var_dump($chain->a->b->c->d->e->f->value());
PHP 8.1.1 - 22.403 ms, 0 Q