Add method in an std object in php

后端 未结 4 1463
说谎
说谎 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:47

    You cannot dynamically add a method to the stdClass and execute it in the normal fashion. However, there are a few things you can do.

    In your first example, you're creating a closure. You can execute that closure by issuing the command:

    $arr['my_method']('Argument')
    

    You can create a stdClass object and assign a closure to one of its properties, but due to a syntax conflict, you cannot directly execute it. Instead, you would have to do something like:

    $node = new stdClass();
    $node->method = function($arg) { ... }
    $func = $node->method;
    $func('Argument');
    

    Attempting

    $node->method('Argument')
    

    would generate an error, because no method "method" exists on a stdClass.

    See this SO answer for some slick hackery using the magic method __call.

提交回复
热议问题