【问题标题】:PHP set class property to retain its value on every callPHP 设置类属性以在每次调用时保留其值
【发布时间】:2015-10-13 20:15:16
【问题描述】:

我知道这是一个简单的问题,抱歉,但我仍在学习 OOP 概念。

我希望有一个在执行期间应保留其值的类属性,我需要通过同一类中的不同方法获取和设置该值。

我的代码:

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 的值已正确设置:

$incarico = new incarico($db);
$incarico->protocollo = $incarico->generaProtocollo();

值为空。 我做错了什么?

谢谢你, 亚历克斯

【问题讨论】:

  • 为什么你希望这个变量是静态的?还有“globale”类的内容是什么?
  • 我希望它是静态的,因为我每次删除记录时都需要一种“增量计数器”来存储和更新。 “globale”类包含我在这种情况下不使用的方法..
  • 你为什么不想使用1个对象和普通方法?阅读有关依赖注入的信息,如果您仍然学习,您的代码也很难阅读,我建议您在养成坏习惯之前阅读 PSR。 $stmt->execute() 并不意味着删除了行,而是执行了该查询,我认为您会查找 PDO rowCount() 方法给出的受影响的行
  • 谢谢@罗伯特。我已经阅读了依赖注入(非常理解)和 PSR(需要更多研究)文章,我应该这样做:使用 setter 方法创建一个新的 $contatore 类,该方法的参数依赖于 incarico 的 delete() 方法。 . 对吗?

标签: php oop static


【解决方案1】:

试试这个代码:

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();
    }
}

你需要做的是:

  1. 用英文写代码真的很有帮助,而且代码更易读。
  2. 使用 PSR 标准
  3. 您需要使用不像 Global 这样的类,不要以全局方式思考,尝试将您的想法转变为 DI 和具有非全局状态的对象。
  4. 我没有在课堂上写,但是使用 getter 和 setter 是个好习惯
  5. 我不认为计数行应该在名为 delete 的方法中。您可能应该创建其他计算行数的方法

用法:

$obj = new Incranico();
$obj->delete();
echo $obj->countRows();
$obj->delete();
echo $obj->countRows();

我真的不知道您的需求是什么,但删除方法也可以使用 $id 的参数,这样会更清楚。

【讨论】:

    【解决方案2】:

    可能是您的$stmt->execute()query() 返回错误。请注意,$annocorrente 也永远不会设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 2012-09-28
      • 1970-01-01
      相关资源
      最近更新 更多