I am wondering that whether it is possible to write two different mysql queries in one php class object method and use those results in an another class method. Here's I am trying to do (I put only the relevant part of my code here), but I think it's not working:
<?php
public function sql()
{
$sql = "SELECT * FROM customers";
// Another sql
$sql_sales = "SELECT SUM(sales) as sales FROM customers";
// Execute this sql and result is stored in a variable
$this->sales = $row['sales'];
return $sql;
}
public function customers_list()
{
$sql = $this->sql();
$customers = '
<div id="customers">
<div id="customers_num"><span>'.$this->sales.'</span> Sales</div>
</div>';
return $customers;
}
?>
Can we use value of variable $this->sales
inside another method?
If not then what's the correct way of getting it's value?
In case your code is inside a class and you're using an instantiated object :
From PHP basics
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object
Therefore you can access any of your object properties inside its methods.
In your specific case $this->sales = $row['sales'];
stores a value in its sales
property which can be used anywhere else in the object scope.
We can not get variable value like your approach. Your main query $sql
is returning the result but the value of your second query $sql_sales
is nowhere returned. That's why it is undefined property in your method customers_list()
.
The solution is to create a separate method to get $this->sales
value. Then you can call this method in your customers_list()
and access its value.