Dynamically create PHP class functions

前端 未结 3 1313
遇见更好的自我
遇见更好的自我 2020-12-08 15:40

I\'d like to iterate over an array and dynamically create functions based on each item. My pseudocode:

$array = array(\'one\', \'two\', \'three\');

foreach          


        
相关标签:
3条回答
  • 2020-12-08 16:12

    Not sure about the usage in your case, you can use create_function to create anonymous functions.

    0 讨论(0)
  • 2020-12-08 16:16

    Instead of "creating" functions, you can use the magic method __call(), so that when you call a "non-existent" function, you can handle it and do the right action.

    Something like this:

    class MyClass{
        private $array = array('one', 'two', 'three');
    
        function __call($func, $params){
            if(in_array($func, $this->array)){
                return 'Test'.$func;
            }
        }
    }
    

    Then you can call:

    $a = new MyClass;
    $a->one(); // Testone
    $a->four(); // null
    

    DEMO: http://ideone.com/73mSh

    EDIT: If you are using PHP 5.3+, you actually can do what you are trying to do in your question!

    class MyClass{
        private $array = array('one', 'two', 'three');
    
        function __construct(){
            foreach ($this->array as $item) {
                $this->$item = function() use($item){
                    return 'Test'.$item;
                };
            }
        }
    }
    

    This does work, except that you can't call $a->one() directly, you need to save it as a variable.

    $a = new MyClass;
    $x = $a->one;
    $x() // Testone
    

    DEMO: http://codepad.viper-7.com/ayGsTu

    0 讨论(0)
  • 2020-12-08 16:30
    class MethodTest
    {
        private $_methods = array();
    
        public function __call($name, $arguments)
        {
            if (array_key_exists($name, $this->_methods)) {
                $this->_methods[$name]($arguments);
            }
            else
            {
                $this->_methods[$name] = $arguments[0];
            }
        }
    }
    
    $obj = new MethodTest;
    
    $array = array('one', 'two', 'three');
    
    foreach ($array as $item) 
    {
        // Dynamic creation
        $obj->$item((function ($a){ echo "Test: ".$a[0]."\n"; }));
        // Calling
        $obj->$item($item);
    }
    

    The above example will output:

    Test: one
    Test: two
    Test: three
    
    0 讨论(0)
提交回复
热议问题