wordpress user wordpress user - 5 months ago 17
MySQL Question

Returning query value in OOP

I am learning OOP. My question is based on below code. Each time the value is returned in index.php using

$query_value->GetName()
or
$query_value->GetId()
.

Is it running the MySQL query each time because of
$query_value
?

In 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;
}
}


In index.php

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

Answer

Is it running the mysql query each time?(because of $query_value)

No, it's not running the query each time. With this statement $query_value = $test->query();, you executed the query once and set the instance properties using $this->name, $this->id and $this->password.

And in these statements $query_value->GetName(); and $query_value->GetId();, you're only accessing the getter methods of your OOP class to get the name and id values, that's it.

Comments