什么是回调函数以及如何在 OOP 中使用它
我想使用 php 简单的 HTML DOM 解析器 来抓取图片、标题、日期,以及在充满文章的页面上对每篇文章的描述.在查看 API 时,我注意到它有一个 set_callback,它设置了一个回调函数.但是我不确定这是做什么或我将如何使用它?在其中一个示例中,它用于调用一个删除一些内容的函数,我想知道您是否必须使用它来调用所有函数?
I want to use the php simple HTML DOM parser to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set_callback which Sets a callback function. However im not sure what this does or how I would use it? In one of the examples its used to call a function which strips out some stuff, im wondering if you have to use this to call all functions?
我想我想知道为什么要使用它,它有什么作用,因为我以前从未遇到过回调函数!
I guess im wondering why I use this, and what does it do as I have never come across a callback function before!
推荐答案
这是一个基本的回调函数示例:
Here's a basic callback function example:
<?php
function thisFuncTakesACallback($callbackFunc)
{
echo "I'm going to call $callbackFunc!<br />";
$callbackFunc();
}
function thisFuncGetsCalled()
{
echo "I'm a callback function!<br />";
}
thisFuncTakesACallback( 'thisFuncGetsCalled' );
?>
您可以调用一个函数,其名称存储在这样的变量中:$variable().
You can call a function that has its name stored in a variable like this: $variable().
因此,在上面的示例中,我们将 thisFuncGetsCalled 函数的名称传递给 thisFuncTakesACallback(),然后后者调用传入的函数.
So, in the above example, we pass the name of the thisFuncGetsCalled function to thisFuncTakesACallback() which then calls the function passed in.
相关文章