21

このようにメソッド/関数を追加することは可能ですか?

$arr = array(
    "nid"=> 20,
    "title" => "Something",
    "value" => "Something else",
    "my_method" => function($arg){....}
);

または多分このように

$node = (object) $arr;
$node->my_method=function($arg){...};

可能であれば、その関数/メソッドをどのように使用できますか?

4

5 に答える 5

0

別の解決策は、匿名クラスを作成し、魔法の関数を介して呼び出しをプロキシする__callことです。アロー関数を使用して、コンテキスト変数への参照を保持することもできます。

 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);
            }

    }
于 2020-04-30T16:27:46.500 に答える