【问题标题】:php: variable scope within a classphp:类内的变量范围
【发布时间】:2015-03-10 10:11:24
【问题描述】:

我开始学习类并且有一个可变范围的问题。我在一个函数中定义了一个变量 $query 并且需要在第二个函数中使用它。但是,第二个函数没有看到它。

我想我可以将 $query 传递到类外部,然后将其传递 ($instance->QueryExecute($query);)。但这看起来很乱,$query 没有必要存在于类之外。

解决这个问题的正确方法是什么?

谢谢你, 路易斯。

<?php
class MyProduct {
    public function QueryBuild() {
        $query = "SELECT * FROM my_product";
    }
    public function QueryExecute() {
        $result = mysql_query($query);
        while ($record = mysql_fetch_assoc($result)) {
            foreach ($record AS $key => $value) {
                $this->product[$record["pro_id"]][$key] = $value;
            }
        }
    }
}
?>

【问题讨论】:

    标签: php class scope


    【解决方案1】:

    有两种选择可以解决您的问题,第一种(在我看来)比另一种更好:

    选项一:返回值

    只需告诉你的构建方法返回值,然后在你的其他方法上使用它:

    <?php
    class MyProduct {
        public function QueryBuild() {
            $query = "SELECT * FROM my_product";
            return $query;
        }
        public function QueryExecute() {
            $result = mysql_query($this->QueryBuild());
            while ($record = mysql_fetch_assoc($result)) {
                foreach ($record AS $key => $value) {
                    $this->product[$record["pro_id"]][$key] = $value;
                }
            }
        }
     }
    

    选项 2:对象字段

    您在类中定义一个字段来保存查询。但是,这意味着在调用QueryExecute() 之前总是必须调用方法QueryBuild(),这不是特别合理。

    <?php
    class MyProduct {
        private $query;
        public function QueryBuild() {
            $this->query = "SELECT * FROM my_product";
        }
        public function QueryExecute() {
            $result = mysql_query($this->query);
            while ($record = mysql_fetch_assoc($result)) {
                foreach ($record AS $key => $value) {
                    $this->product[$record["pro_id"]][$key] = $value;
                }
            }
        }
    }
    

    注意事项:

    • 不要使用mysql_* 函数。它们已被弃用,并已被 MySQLi 和 PDO 取代。
    • 查看编码约定。方法名称应以小写字母开头,这样对于习惯于这些标准的每个人来说,代码都更易于阅读。

    【讨论】:

    • 选项 1 是我一直在寻找的绝佳解决方案。通过限制“$this->”的使用,它允许我以更简洁的方式编写代码。谢谢你。是的,我将停止使用 mysql_* ......稍后。
    【解决方案2】:

    您在类中定义了一个属性,表示我想补充一点,mysql_* 函数已被弃用。

    <?php
    class MyProduct {
        private $query;
        public function QueryBuild() {
            $this->query= "SELECT * FROM my_product";
        }
        public function QueryExecute() {
            $result = mysql_query($this->query);
            while ($record = mysql_fetch_assoc($result)) {
                foreach ($record AS $key => $value) {
                    $this->product[$record["pro_id"]][$key] = $value;
                }
            }
        }
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2011-05-21
      • 2013-07-28
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 2010-12-19
      • 2012-01-19
      • 2021-08-21
      相关资源
      最近更新 更多