不能多次实例化同一个类

时间:2013-11-28 03:05:52

标签: php oop

真的,真的很抱歉..似乎问题出在我使用的KLogger上。我从我的代码中删除了KLogger,现在它运行得非常好。从来没有想过一个简单的记录器类会导致问题。

这是我的php类

<?php
session_start(); 

error_reporting(E_ALL);
ini_set('display_errors', '1');
error_reporting(1);

class Gamification {

    private $webAction;
    private $currentLimit;
    private $maxLimit;

    function __construct($getWebAction) {           
        $this->webAction = $getWebAction;

        include ("config.path.php");
        include ($config['BASE_DIR']."/include/KLogger.php");
        $log = KLogger::instance($config['BASE_DIR'].'/log/');

        $log->logInfo('class.gamification.php: line 21: webAction:'.$getWebAction);

    }

    public function getMaxLimit(){
        $this->maxLimit = 99;
        return $this->maxLimit;
    }

    public function getCurrentLimit(){
        $this->currentLimit = 3;
        return $this->currentLimit;
    }
}

?>

我尝试从其他php页面多次实例化它,如下所示:

 $gamification = new Gamification("expensesCategory");
    $currentLimit = $gamification->getCurrentLimit();
    $maxLimit = $gamification->getMaxLimit();

    $gamificationInfoExpFixedMonthly = new Gamification("expensesFixedMonthly");
    $currentLimitExpFixedMonthly = $gamificationInfoExpFixedMonthly->getCurrentLimit();
    $maxLimitExpFixedMonthly = $gamificationInfoExpFixedMonthly->getMaxLimit();

但问题是第二个Gamification类($gamificationInfoExpFixedMonthly)将永远不会被访问/初始化...不会返回任何错误,它只是不会到达那里..该行下面的所有html代码也不会出现......我做错了什么?无论如何,我会尝试更新我的PHP并稍后给出结果

1 个答案:

答案 0 :(得分:0)

你班上有些问题......请看:

首先在构造函数中传递一个从未使用过的变量:

function __construct($belongsTo, $getWebAction) {
                  //       ^this one here what is is doing here???

第二步创建一个使用未定义的局部变量的方法

public function getCurrentLimit($belongsTo) {
    return $currentLimit;
                //^here it should be: $this->currentLimit
}

此外,您必须在课程中定义它才能在您的方法上使用

 //.... some more stuff
private $initialLimit = 3;
private $maxLimit = 10;
private $currentLimit = 0;

还有更多:

public function getCurrentLimit($belongsTo) {
                                 // ^ this is not used at all
    return $currentLimit;
                //^here it should be: $this->currentLimit
}

解决所有问题,它应该有效