Add method in an std object in php

后端 未结 4 1460
说谎
说谎 2021-01-01 14:13

Is it possible to add a method/function in this way, like

$arr = array(
    \"nid\"=> 20,
    \"title\" => \"Something\",
    \"value\" => \"Somethi         


        
4条回答
  •  情书的邮戳
    2021-01-01 14:56

    Another solution would be to create an anonymous class and proxy the call via the magic function __call, with arrow functions you can even keep reference to context variables:

     new Class ((new ReflectionClass("MyClass"))->getProperty("myProperty")) {
                public function __construct(ReflectionProperty $ref)
                {
                    $this->setAccessible = fn($o) => $ref->setAccessible($o);
                    $this->isInitialized = fn($o) => $ref->isInitialized($o);
                    $this->getValue = fn($o) => $ref->getValue($o);
                }
    
                public function __call($name, $arguments)
                {
                    $fn = $this->$name;
                    return $fn(...$arguments);
                }
    
        }
    

提交回复
热议问题