PHP将class属性设置为在每次调用时保留其值
我知道这是一个简单的问题,抱歉,但我仍在学习面向对象的概念 我希望有一个类属性,它在执行过程中应该保留它的值,我需要通过同一个类中的不同方法获取并设置该值 我的代码:PHP将class属性设置为在每次调用时保留其值,php,oop,static,Php,Oop,Static,我知道这是一个简单的问题,抱歉,但我仍在学习面向对象的概念 我希望有一个类属性,它在执行过程中应该保留它的值,我需要通过同一个类中的不同方法获取并设置该值 我的代码: class incarico extends globale { static $contatore; // delete the product function delete(){ $query = "DELETE FROM " . $this->table_name . "
class incarico extends globale {
static $contatore;
// delete the product
function delete(){
$query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);
// on every delete I need to get the total number of records
if($result = $stmt->execute()){
self::$contatore = $this->conn->query("select count(*) from ". $this->table_name)->fetchColumn();
return true;
}
else{
return false;
}
}
function generaProtocollo () {
// here I need the $contatore value
error_log(self::$contatore);
return $annocorrente . self::$contatore;
}
}
当我用
$incarico = new incarico($db);
$incarico->delete()
当我(在之后)调用时,$contatore的值设置正确:
该值为空。
我做错了什么
谢谢,,
Alex可能是您的
$stmt->execute()
或query()
返回了false。请注意,$annocorrente
也从未设置。请尝试以下代码:
class Incarico extends Globale
{
private $contatore;
// delete the product
public function delete()
{
$query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);
return $stmt->execute();
}
public function generaProtocollo ()
{
return $annocorrente . $this->contatore;
}
public function countRows()
{
return $this->contatore = $this->conn->query("select count(*) from ". $this->table_name)->fetchColumn();
}
}
您需要做的是:
$obj = new Incranico();
$obj->delete();
echo $obj->countRows();
$obj->delete();
echo $obj->countRows();
我真的不知道您需要什么,但delete方法也可以使用param,即$id,这样更清楚。为什么您希望这个变量是静态的?还有,“globale”类的内容是什么?我希望它是静态的,因为我需要一种“增量计数器”,每次删除记录时都要存储和更新。“globale”类包含我在本例中不使用的方法。为什么不使用1对象和普通方法?阅读关于依赖注入的内容,如果您仍然学习,那么您的代码也很难阅读。我建议您在养成坏习惯之前阅读PSR
$stmt->execute()
并不意味着行已被删除,但该查询已被执行,我认为您可以查找受影响的行,PDO rowCount()方法为其提供了hank you@Robert。我已经阅读了依赖注入(非常理解)和PSR(需要更多的研究)两篇文章,我会这样做:使用setter方法创建一个新的$contatore类,该方法的参数依赖于Invanico的delete()方法。。。对吗?
$obj = new Incranico();
$obj->delete();
echo $obj->countRows();
$obj->delete();
echo $obj->countRows();