PHP调用类外函数内部匿名函数
嘿,伙计们,我想在类A中调用我的函数,而不是在类B中匿名函数中调用它,怎么做? 这里是我的示例代码PHP调用类外函数内部匿名函数,php,class,anonymous,Php,Class,Anonymous,嘿,伙计们,我想在类A中调用我的函数,而不是在类B中匿名函数中调用它,怎么做? 这里是我的示例代码 <?php class A extends Z{ public function sampleFunction($post){ // code here } } class B extends A{ public __construct(){ $this->anot
<?php
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)
);
}
});
}
}
?>
您需要使用($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));
}
});
}
此外,如果您使用的是PHP5.3,则不能在函数中使用$this
。你需要使用
$that = $this;
add_action(...) use ($post, $that) {
//...
$that->sampleFunction(...)
你有错误吗?你使用的是哪个版本的php?耶。。获取这样的错误
致命错误:当不在对象上下文中时使用$this
我正在使用PHP5.3他们感谢您的回答,已经尝试过了,而且它正在工作,所以如果我想从另一个字符串或变量中使用$
,我必须使用use
?顺便说一句,我得到了一个新错误致命错误:在一个非对象上调用成员函数resetParameters()
我在wordpress插件中使用zend gdata。