PHP在匿名函数内调用外部类函数

发布时间:2021-07-27 16:25:58 阅读:1290次

https://m.656463.com/wenda/PHPznmhsndywblhs_491

我想在A类中调用我的函数而不是在匿名函数内的B类中调用它怎么做? 这是我的示例代码。


class A extends Z{
public function sampleFunction($post){
// code here
}

}

class B extends A{
public __construct(){
$this->anotherClass();
}
// add_action() and update_meta_box() is function from wordpress

public function anotherClass(){
$post = $_POST['test'];
add_action('save_post',function($id){
if(isset($post)){
// here i dont know how to call it inside anonymous function
$this->sampleFunction($post);
update_meta_box(
$id,
'key',
strip_tags($post)
);
}
});
}

}

?>

hey guys i wanna call my function inside class A than call it inside class B within anonymous function how to do that ? here my sample code.


class A extends Z{
public function sampleFunction($post){
// code here
}

}

class B extends A{
public __construct(){
$this->anotherClass();
}
// add_action() and update_meta_box() is function from wordpress

public function anotherClass(){
$post = $_POST['test'];
add_action('save_post',function($id){
if(isset($post)){
// here i dont know how to call it inside anonymous function
$this->sampleFunction($post);
update_meta_box(
$id,
'key',
strip_tags($post)
);
}
});
}

}

?>

原文:https://stackoverflow.com/questions/20437747
2020-02-16 01:53
满意答案
您需要use ($post)使其在匿名函数中可访问。
public function anotherClass(){
$post = $_POST['test'];
add_action('save_post', function($id) use ($post) {
if(isset($post)) {
$this->sampleFunction($post);
update_meta_box($id, 'key', strip_tags($post));
}
});
}

此外,如果您使用的是php 5.3,则无法在函数中使用$this 。 你需要使用
$that = $this;
add_action(...) use ($post, $that) {
//...
$that->sampleFunction(...)

You need to use ($post) to make it accessible within the anonymous function.
public function anotherClass(){
$post = $_POST['test'];
add_action('save_post', function($id) use ($post) {
if(isset($post)) {
$this->sampleFunction($post);
update_meta_box($id, 'key', strip_tags($post));
}
});
}

Also, if you are using php 5.3, you cannot use $this within the function. You need to use
$that = $this;
add_action(...) use ($post, $that) {
//...
$that->sampleFunction(...)  


如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明:PHP在匿名函数内调用外部类函数 出自老鄢博客 | 欢迎分享