2013-09-27 99 views
-1

嘿,我是PHP新手,但我知道Java的基本知識,並瞭解Java中的面向對象,但我試圖理解如何使它通過面向對象與HTML交織。爲什麼下面的代碼不會回傳消息?謝謝。我的PHP OOP在哪裏錯了?

<?php 

class SubmitPost { 

    public function __construct() { 
     $Db = new PDO('mysql:host=localhost;dbname=Comment', 'root', ''); 
    } 

    public function Comment($Post, $Time, $Title) { 

     $Post = strip_tags($_POST['Post']); 
     $Time = time(); 
     $Title = strip_tags($_POST['Title']); 

      $Messages = array('success' => 'Your comment has been added.', 'error' => 'There was a problem adding your comment.'); 

       if(isset($Post, $Title)) { 
        return $Messages['success']; 
       } else { 
        return $Messages['error']; 
       } 

    } 
} 

$New = new SubmitPost; 
var_dump($New); 
?> 

<html> 
    <head> 
    </head> 

    <body> 
     <form action="OO.php" method="POST"> 
      <input type="text" name="Title" placeholder="Your Title"><br /> 
      <textarea placeholder="Your Comment" name="Post"></textarea><br /> 
      <input type="submit" value="Comment"> 
     </form> 
    </body> 
</html> 
+3

你是不是執行'Comment'功能,只需構造。而且它似乎並不需要參數。 – elclanrs

+0

檢查請求類型是否發佈,然後運行'$ New-> Comment()'。 (無論如何,所有的參數都不會被使用,它們被設置在函數中。) –

+0

沒有任何屬性的類? –

回答

1

您需要在某處調用您的方法。

$New = new SubmitPost(); 
echo $New->Comment("needless","because","unused"); // You are not using these values in your method 
//var_dump($New); 

編輯 這不是一個真正的OOP。它應該像

public function Comment($Post, $Time, $Title) { 
    $Post = strip_tags($Post); 
    $Title = strip_tags($Title); 
    //.... 
    } 

,並調用它像

$New = new SubmitPost(); 
echo $New->Comment($_POST["Post"],time(),$_POST["Title"]); 
0

您的對象沒有任何東西。這就是爲什麼你沒有得到任何輸出。請嘗試以下代碼:

<?php 

class SubmitPost { 
    public $test; 
    public function __construct() { 
     $Db = new PDO('mysql:host=localhost;dbname=comment', 'root', ''); 
     $this->test = "yahoo"; 
    } 

    public function Comment($Post, $Time, $Title) { 

     $Post = strip_tags($_POST['Post']); 
     $Time = time(); 
     $Title = strip_tags($_POST['Title']); 

      $Messages = array('success' => 'Your comment has been added.', 'error' => 'There was a problem adding your comment.'); 

       if(isset($Post, $Title)) { 
        return $Messages['success']; 
       } else { 
        return $Messages['error']; 
       } 

    } 
} 

$New = new SubmitPost; 
var_dump($New); 
+0

那麼我怎樣才能讓我寫作的功能呢? –

+0

@John:按照Hanky웃Panky的回覆。 –