2011-01-05 23 views
1

海蘭傢伙,致命錯誤:調用未定義功能reg_form()在C: XAMPP htdocs中 PHP PHP BEGINNING 5 mysql的 form_test.php上線18

我是新來的PHP,該我指的是PHP書 - 「可以在實際函數定義出現在代碼中之前調用函數」。在下面的代碼中,我正在調用_reg_form(); _函數在下面定義之前,但我得到的錯誤。我究竟做錯了什麼。

感謝您的關注。

<?php 
include('common_db.inc'); 
include('validation.php'); 

if(!$link=db_connect()) die(sql_error()); 
if($_POST['submit']) 
{ 
    $userid = $_POST['userid']; 
    $userpassword=$_POST['userpassword']; 
    $username=$_POST['username']; 
    $userposition = $_POST['userposition']; 
    $useremail=$_POST['useremail']; 
    $userprofile=$_POST['userprofile']; 
    $result=validate(); 
    if($result==0) 
    { 
    reg_form(); 
    } 
else 
{ 
    mysql_query("INSERT INTO user VALUES(NULL,'$userid',Password('$userpassword'),'$username','$userposition','$useremail','$userprofile')",$link); 
} 
} 
else 
{ 
?> 
<?php 
function reg_form() 
{ 
echo "<table border='1'> 
<form action='form_test.php' method='post'> 
    <tr><td>Desired ID:</td> 
    <td><input type='text' size='12' name='userid' /></td></tr> 
    <tr><td>Desired Password:</td> 
    <td><input type='password' size='12' name='userpassword' /></td></tr> 
    <tr><td><input type='hidden' name='submit' value='true' /> 
    <input type='submit' value='Submit' /> 
    <input type='reset' value='Reset' /></td></tr> 
</form> 
</table>"; 
} 

    reg_form(); 
?> 
<?php 
} 
?> 
+0

爲什麼不先定義函數?我不確定你在做什麼是可能的(我猜不是),但那不是很重要,因爲它在任何情況下都會是可怕的編碼風格 – Hannes 2011-01-05 13:16:40

回答

2

您正在定義一個條件函數。 The manual you are referring to說,這(重點煤礦):

Functions need not be defined before they are referenced, except when a function is conditionally defined

您的代碼,縮短:

if ($something) { 
    reg_form(); // use function (not defined) 
} else { 
    function reg_form() { 
     // define function only if (!$something) 
    } 
} 

因此,你的功能僅在其他分支定義。你需要這樣的事情,在這裏總是執行你的函數的定義:

if ($something) { 
    reg_form(); // use function (already defined since the script was loaded) 
} else { 
    // something else 
} 

// not conditional - will be loaded when script starts 
function reg_form() { 
    // define function 
} 
0

您定義if()塊的else子句中的功能。最有可能的函數調用從其他塊之一存在的,所以功能還沒有被在調用的時候解析:

if (..) { 
    reg_form(); 
} else { 
    function reg_form() { ... } 
} 

將無法​​正常工作。應該在代碼的頂層定義函數,而不在任何函數或邏輯結構之外。

0

你的功能reg_form的範圍中,它被稱爲外部定義。

+0

PHP沒有像這樣的函數範圍的概念。一個有條件定義的全局函數仍然存在於全局範圍內,但是直到包含其定義的代碼分支被執行之後它纔會出現。 – Piskvor 2011-01-05 13:19:59

相關問題