【问题标题】:Returning query value in OOP在 OOP 中返回查询值
【发布时间】:2016-06-16 21:10:32
【问题描述】:

我正在学习 OOP。我的问题基于以下代码。每次使用$query_value->GetName() 或$query_value->GetId() 在index.php 中返回值。

是不是因为$query_value而每次都运行MySQL查询?

在 Class.php 中

  <?php
class OOP{
    public $name,$id,$password

    public function query(){
        /* Query Performed
           rowCount() = 1 */
           $this->name = returned row  value;
           $this->id =  returned row  value;
           $this->password= returned row  value;
           return $this; // [NOTE THIS ($this)]

    }
    public function GetName(){
        return $this->name;
    }
    public function GetId(){
        return $this->id;
    }
}

在 index.php 中

 <?php
 $test=  new OOP();
 $query_value = $test->query();
 // now returning values
 echo $query_value->GetName();
 /// Some Html
 echo $query_value->GetId();
 ?>

【问题讨论】:

    标签: php mysql oop


    【解决方案1】:

    是否每次都运行mysql查询?(因为$query_value)

    不,它不是每次都运行查询。使用此语句$query_value = $test-&gt;query();,您执行了一次 查询并使用$this-&gt;name、$this-&gt;id 和$this-&gt;password 设置实例属性。

    在这些语句$query_value-&gt;GetName(); 和$query_value-&gt;GetId(); 中,您只需要访问OOP 类的getter 方法来获取name 和id 值,就是这样。

    【讨论】:

      【解决方案2】:

      不,它不是每次都查询,因为在实例化 $query_value 变量时已经调用了初始 query() 函数。事实上,你有一个 $test 对象,你不应该需要一个额外的变量来回显值

      $test = new OOP();
      $test->query();
      
      // echo out the values
      
      echo $test->GetName();
      echo $test->GetId();
      

      那么您不需要在 query() 函数中返回 $this,因为 $test 是对象变量并且已经设置了这些值。

      【讨论】:

        【解决方案3】:

        不,因为您只调用该函数一次。 GetName 和 GetId 是该类的独立方法。

        但我要做的是像这样调用 getter 方法:

        echo $test->GetName();
        echo $test->GetId();
        

        这更容易理解。并且您的 query() 方法将这些值归档。你所做的只是将你的类分配给不同的变量。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-19
          • 2021-07-07
          • 2018-04-11
          • 1970-01-01
          • 2019-03-21
          • 2018-03-15
          相关资源
          最近更新 更多