简体   繁体   English

函数回调(PHP)无法正常工作

[英]Callback in function (PHP) is not working

When I execute following code I am getting this error. 当我执行以下代码时,出现此错误。 Why is that? 这是为什么? What is the proper use of callbacks? 回调的正确用法是什么?

CODE (simplified) CODE(简体)

class NODE {
  //...some other stuff
  function create($tags, $callback=false) {
    $temp = new NODE();
    //...code and stuff
    if($callback) $callback($temp); //fixed (from !$callback)
    return $this;
  }
}
$document = new NODE();
$document->create("<p>", function($parent) {
$parent->create("<i>");
});

ERROR 错误

Fatal error: Function name must be a string in P:\htdocs\projects\nif\nif.php on line 36
$document->new NODE();

This is not valid syntax. 这是无效的语法。 The accepted format would be: 可接受的格式为:

$document = new NODE();

In addition to this, if you use the unary operator ( ! ) on a false, you get true. 除此之外,如果对false使用一元运算符( ! ),则为true。 If you use it on a Callable , you get false. 如果在Callable上使用它,则会得到false。 As such, if (!$callback) $callback() will throw the first error of your script. 这样, if (!$callback) $callback()将抛出脚本的第一个错误。

As a side note, you are reinventing the wheel. 附带说明,您正在重新发明轮子。 I would strongly recommend you take a look at the DOMDocument family of classes, which are doing exactly what you are currently trying to implement, albeit with fewer callbacks. 我强烈建议您看一下DOMDocument系列类,这些类DOMDocument在执行您当前要实现的功能,尽管回调次数较少。

if(!$callback) $callback($temp);

should probably be 应该是

if($callback) $callback($temp);

And the instanciation: 和实例:

$document = new NODE();
if(!$callback) $callback($temp);

如果$callbackfalse ,请确保您无法将其作为回调调用。

My 2c here, type hinting may be good to use here as well. 我在这里的2c,也可以在这里使用类型提示。

Ex: function create($tags, callable $callback = function()) 例如: function create($tags, callable $callback = function())

To do such a thing in php you should use function pointers and tell php which function to execute. 要在php中执行此操作,您应该使用函数指针,并告诉php执行哪个函数。 Look at this code. 看这段代码。

// This function uses a callback function.
function doIt($callback)
{
    $data = acquireData();
    $callback($data);
}


// This is a sample callback function for doIt().
function myCallback($data)
{
    echo 'Data is: ', $data, "\n";
}


// Call doIt() and pass our sample callback function's name.
doIt('myCallback');  

So as you seen you can only pass the name to the function and you should predefine the function.. 因此,如您所见,您只能将名称传递给函数,并且应该预定义函数。

Similar question: How do I implement a callback in PHP? 类似的问题: 如何在PHP中实现回调?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM