我已經試着Google如何做到這一點,但我仍然無法弄清楚。如何在PHP中創建一個簡單的鉤子?以下是我試過到目前爲止:PHP如何創建簡單的鉤子?
wrapper.php(應用程序從這裏開始)
<?php require 'core.php'; ?>
<?php require 'view.php'; ?>
core.php中
<?php
$hooks['hook_head'] = array();
//supposed to insert action in $hooks
function addHook($hookName, $funct){
global $hooks;
array_push($hooks[$hookName], $funct);
}
//supposed to execute specific hook
function executeHook($hookname){
global $hooks;
foreach($hooks[$hookname] as $funct){
call_user_func($funct);
}
}
//supposed to execute action in $hooks when array key = hook_head
function hook_head(){
global $hooks;
if (array_key_exists('hook_head', $hooks)) {
executeHook('hook_head');
}
}
//supposed to execute action in $hooks when array key == hook_footer
function hook_footer(){
global $hooks;
if (array_key_exists('hook_footer', $hooks)) {
executeHook('hook_footer');
}
}
?>
view.php
<!DOCTYPE HTML>
<html>
<head>
<?php hook_head(); ?>
</head>
<body>
<hr />
<?php
//add action to hook start here
$test = function(){ echo "test succeds"; };
addHook('hook_head', $test);
?>
<?php hook_footer(); ?>
</body>
</html>
如果我在$hooks['hook_head']
之內插入一個動作,則在我致電hook_head()
之前,該代碼正常工作。我實際上想要做的是在我打電話給hook_head()
之後插入操作。我該怎麼做呢?
的直觀的控制流不知道你知道一個鉤子是什麼。 – FaddishWorm
你確實想爲每個'鉤子名'有多個功能? – robbmj
@FaddishWorm好吧,我開始懷疑我對鉤子的瞭解。我只想從身體標記中迴應標籤頭中的內容。 – ilike