2015-06-26 47 views
-2

我想獲得一個類內函數的值。在一個類和函數之外訪問變量

classes.php

class luresClass { 

    public function lureSelect() { 

    global $lureChoice; 
    if ($_POST['airtemp'] == 2 && $_POST['watertemp'] == 5) { 
      $lureChoice = 1; 
     } 
    else {$lureChoice = 0;} 

} 

} 

這是主文件(的index.php)需要訪問$ lurechoice的價值。

if (isset($_POST['submit'])) { 

$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); 

    $displayLureChoice = new luresClass(); 
    $displayLureChoice->lureSelect(); 
    $stmt = $conn->prepare("SELECT * FROM ".$tbl."lure WHERE id = ".$lureChoice."");  
    $stmt->execute(); 

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ 
      echo "Lure Choice: ".$row['type']. "<br />Color: " .$row['color']. "<br /><br />"; 
    } 
} 

用戶從表單中選擇某些項目,它將返回if/else值。

我已經嘗試使$ lurechoice在函數lureSelect()中的classes.php文件中的全局變量,但不起作用。我嘗試將它作爲課堂上的公開變體,但也失敗了。

感謝您的指導。

回答

1

你並不需要使用您只需設置在你的類的全局變量,然後使用一個函數傳回:

class luresClass { 

    public $lureChoice; 

    public function lureSelect() { 

     if ($_POST['airtemp'] == 2 && $_POST['watertemp'] == 5) { 

      $this->lureChoice = 1; 
     } 
     else { 
      $this->lureChoice = 0; 
     } 
    } 

    public function getLureChoice(){ 
     return $this->lureChoice; 
    } 

} 

代碼

$displayLureChoice = new luresClass(); 
$displayLureChoice->lureSelect(); 

$lureChoice = $displayLureChoice->getLureChoice(); 

$stmt = $conn->prepare("SELECT * FROM ".$tbl."lure WHERE id = ".$lureChoice."");  
$stmt->execute(); 

while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ 
    echo "Lure Choice: ".$row['type']. "<br />Color: " .$row['color']. "<br /><br />"; 
} 
+0

啊,這是返回我沒有得到的值的函數。我通過挑選代碼來學習。這個答案有效。 – user4742637