的Theres此WordPress插件称为忍者形式,http://developer.ninjaforms.com/codex/merge-tags/如何在foreach循环php中创建一个函数?
/* Individual tag registration. */
$this->merge_tags = array(
'foo' => array(
'id' => 'foo',
'tag' => '{my:foo}', // The tag to be used.
'label' => __('Foo', 'my_plugin'), // Translatable label for tag selection.
'callback' => 'foo' // Class method for processing the tag. See below.
),
);
/*
* Use the `init` and `admin_init` hooks for any necessary data setup that relies on WordPress.
* See: https://codex.wordpress.org/Plugin_API/Action_Reference
*/
add_action('init', array($this, 'init'));
add_action('admin_init', array($this, 'admin_init'));
}
public function init(){ /* This section intentionally left blank. */ }
public function admin_init(){ /* This section intentionally left blank. */ }
/**
* The callback method for the {my:foo} merge tag.
* @return string
*/
public function foo()
{
// Do stuff here.
return 'bar';
} } '回调' 的
值随后被用作一个函数,公共函数(富)。
我已经加入这个数组:
[foo] => Array
(
[id] => foo
[tag] => {my:foo}
[label] => Foo
[callback] => foo
)
[surveyid] => Array
(
[id] => surveyid
[tag] => {my:surveyid}
[label] => Surveyid
[callback] => surveyid
)
[membername] => Array
(
[id] => membername
[tag] => {my:membername}
[label] => Membername
[callback] => membername
)
香港专业教育学院增加了更多的阵列格式同此阵,和ID喜欢让自己的“回调”值的公共职能,因为他们有。
/**
* The callback method for the {my:foo} merge tag.
* @return string
*/
public function foo()
{
// Do stuff here.
return 'bar';
}
虽然我打算多次这样做,我可能会在未来添加更多的阵列。所以我想动态分配每个数组回调值的公共函数。
这就是我所拥有的。
$data = array(
'@attributes' => array(
'surveyid' => 'V54236',
'membername' => 'John Smith',
));
$realThing = array();
foreach($data['@attributes'] as $key => $value) {
$realThing[$key] = array(
'id' => $key,
'tag' => '{my:'.$key.'}',
'label' => __(ucfirst($key), 'my_plugin'),
'callback' => $key
);
}
$this->merge_tags = $realThing;
add_action('init', array($this, 'init'));
add_action('admin_init', array($this, 'admin_init'));
}
public function init(){ /* This section intentionally left blank. */ }
public function admin_init(){ /* This section intentionally left blank. */ }
}
我尝试为每个回调值分配函数。
foreach($realThing as $key => $value){
public function $key['callback'](){
return $data['@attributes'][$key];
}
};
期望的输出:
public function foo()
{
// Do stuff here.
return 'bar';
}
public function surveyid()
{
// Do stuff here.
return 'V54236';
public function membername()
{
// Do stuff here.
return 'John Smith';
所有帮助理解。
也越来越:在
我想在理论上你可以在循环中创建一个匿名函数。更大的问题是你为什么要这么做?这种smart-alec编码可能会导致难以维护的混乱。 – GordonM