2010-11-16 34 views
5

我試圖從book運行一些代碼。代碼看起來有問題。錯誤信息:致命錯誤:無法在寫入上下文中使用函數返回>值

以下是錯誤消息:

Fatal error: Can't use function return value in write context in /Applications/MAMP/htdocs/Eclipse-Workspace/simpleblog/test.php on line 24

這裏是在消息中所引用的代碼(關於第24行開始)

if (!empty(trim($_POST['username'])) 
     && !empty(trim($_POST['email']))) { 
     // Store escaped $_POST values in variables 
      $uname = htmlentities($_POST['username']); 
      $email = htmlentities($_POST['email']); 

      $_SESSION['username'] = $uname; 

      echo "Thanks for registering! <br />", 
       "Username: $uname <br />", 
       "Email: $email <br />"; 
     } 

我希望得到任何幫助。請讓我知道如果我需要提供更多信息


非常感謝你們。這非常快。該解決方案效果很好。

問題是empty()函數只需要應用於直接變量。

以供將來參考: 代碼是由賈森Lengstorf(2009年),90-91頁,第3章 '絕對初學者PHP',$ _SESSION

糾正代碼:

//new - Created a variable that can be passed to the empty() function 
    $trimusername = trim($_POST['username']); 

    //modified - applying the empty function correctly to the new variable 
    if (!empty($trimusername) 
    && !empty($trimusername)) { 

    // Store escaped $_POST values in variables 
    $uname = htmlentities($_POST['username']); 
    $email = htmlentities($_POST['email']); 

    $_SESSION['username'] = $uname; 

    echo "Thanks for registering! <br />", 
     "Username: $uname <br />", 
     "Email: $email <br />"; 
} 

回答

6

簡言之:empty()功能僅直接變量

<?php 
empty($foo); // ok 
empty(trim($foo)); // not ok 

我會說,對於該書進一步獲取的過程中,只使用一個臨時變量

所以更改:

if (!empty(trim($_POST['username'])) 

$username = trim($_POST['username']); 
if(!empty($username)) { 
    //.... 
+0

非常感謝。這工作。如果有人使用本書並遇到問題,我已更新了更正後的代碼。 – ntc 2010-11-16 09:30:22

+1

非常感謝您使用正確的代碼詢問和回答此問題。我是PHP和編程新手,當我在書中碰到一個錯字時,我幾乎總是認爲它只是我沒有得到它而已。把正確的東西放進去並看到它工作真是太好了! – 2011-02-15 21:28:08

+0

我認爲應該指出,這種行爲隻影響PHP版本<5.5,如 [php.function.empty](http://php.net/manual/en/function.empty.php) – 2015-08-13 05:07:00

3

究竟你的例子是在手動

Note:

empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).

使用提到一個臨時變量,或對「空只是測試字符串「

if (trim($foo) !== '') { 
    // Your code 
} 
+0

謝謝塞巴斯蒂安。 有沒有什麼辦法可以從錯誤信息中推斷出問題出在這個函數上?在這一點上我不太瞭解他們。 – ntc 2010-11-16 09:27:18

+0

一些方法將參數作爲參考,因此它們只接受變量,因爲它們是唯一的參數。 「通過引用傳遞」通常意味着函數*可能*要寫入此變量(這也會影響函數外部的變量值)。也就是說,該消息試圖說明什麼:「empty」(爲什麼)不能寫入函數的返回值,只能寫入變量。 – KingCrunch 2010-11-16 13:16:47

相關問題