如何使用能够在调用函数时定义的节来组合函数?
<?php
class MyClass {
function doSomething() {
$conn = $this->connectToDatabase("database");
$rows = $conn->query($query);
if ($rows->num_rows > 0) {
while($row = $rows->fetch_assoc()) {
$col_value = $row['name'];
function defineMe() {
//i need to be defined when called
}
}
} else {
echo "0 results";
}
$conn->close();
}
}
?>
这样,说我想从数据库中提取数据,我可以更改defineMe()以匹配其吐出的信息的布局。如何覆盖此函数并仍然可以从doSomething()函数访问数据?
像
$myClass = new MyClass;
$myClass->doSomething(){
function defineMe() {
echo $col_value;
}
};
答案 0 :(得分:3)
您可以将回调传递给您的函数:
<?php
class MyClass
{
function doSomething(callable $callback)
{
$conn = $this->connectToDatabase("database");
$rows = $conn->query($query);
if ($rows->num_rows > 0)
{
while($row = $rows->fetch_assoc())
{
$col_value = $row['name'];
$callback($col_value); // Call callback
}
} else {
echo "0 results";
}
$conn->close();
}
}
$myClass = new MyClass;
$myClass->doSomething(function($col_value) {
echo "Inside callback: ".$col_value;
});
?>