【问题标题】:Accessing variables outside of a class and function [closed]访问类和函数之外的变量[关闭]
【发布时间】:2015-06-26 14:53:06
【问题描述】:

我正在尝试获取类中函数的值。

classes.php

 class luresClass {

  public function lureSelect() {

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

 }   

}

这是需要访问$lurechoice值的主文件(index.php)。

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 值。

我尝试在 classes.php 文件中的函数 lureSelect() 中将 $lurechoice 设为全局变量,但不起作用。我尝试将其设为课堂上的公共变量,但也失败了。

感谢您的指导。

【问题讨论】:

    标签: php class variables


    【解决方案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 />";
    }
    

    【讨论】:

    • 啊,是我没有得到的返回值的函数。我通过分解代码来学习。这个答案有效。
    猜你喜欢
    • 2021-05-28
    • 2017-09-11
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2014-04-09
    • 2014-07-11
    • 1970-01-01
    • 2019-09-15
    相关资源
    最近更新 更多