我想知道是否可以在一个 php 类对象方法中编写两个不同的 mysql 查询,并在另一个类方法中使用这些结果。这是我正在尝试做的事情(我只将代码的相关部分放在这里),但我认为它不起作用:
<?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;
}
?>
我们可以在另一个方法中使用变量$this->sales
的值吗?
如果不是,那么获取其值的正确方法是什么?
最佳答案
如果您的代码位于类内部并且您使用的是实例化对象:
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object
因此,您可以在其方法内访问任何对象属性。
在您的具体情况下 $this->sales = $row['sales'];
在其 sales
中存储一个值
属性可以在对象范围内的任何其他地方使用。
关于php - 我们可以在 php 类的一个方法中使用两个 mysql 查询吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57285820/