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

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(...)  

    A+
发布日期:2021年07月27日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: