【问题标题】:PHP : "Fatal error: Using $this when not in object context in" [duplicate]PHP:“致命错误:不在对象上下文中使用 $this” [重复]
【发布时间】:2015-06-30 07:52:32
【问题描述】:

我想为许可证管理器创建一个类,但是,我必须使用另一个类来做我需要在 __construct 类中创建到数据库的新连接。

当我尝试使用一个函数时,在这种情况下是 getAll,我有一个 PHP 错误出现在屏幕上:

致命错误:在 [...] 第 112 行的对象上下文中使用 $ this WHEN NOT。

这是我的课:

class cLicences {

    // Contient les valeurs à afficher
    protected $iLicID                = null;
    protected $sLicProduct           = null;
    protected $sLicDesc              = null;
    protected $sLicKey               = null;
    protected $iLicDateAdded         = null;
    protected $iLicDateEdited        = null;
    protected $iLicUserAdded         = null;
    protected $iLicUserEdited        = null;

    // Connexion à la base de données
    private $oLicMySQL               = null;

    // Contient les noms des champs dans la db
    private static $sFieldID         = 'id_licence';
    private static $sFieldProduct    = 'lic_product';
    private static $sFieldDesc       = 'lic_desc';
    private static $sFieldKey        = 'lic_key';
    private static $sFieldDateAdded  = 'lic_date_added';
    private static $sFieldDateEdited = 'lic_date_edited';
    private static $sFieldUserAdded  = 'idx_user_added';
    private static $sFieldUserEdited = 'idx_user_edited';

    // Nom de la table
    const TABLENAME = 't_licences';

    /**
     * Initialisation de l'objet
     * @param int $iLicID -> ID de la licence
     */
    public function __construct($iLicID = null) {

        // Si l'ID est un ID (numérique donc)
        if(is_numeric($iLicID)) {

            // Stock la connexion dans la classe
            $this->oLicMySQL = new cMySQLi(DB_USERNAME,DB_PASSWORD,DB_HOSTNAME,DB_HOSTPORT,DB_DATABASE);

            // Initialise l'ID de la classe avec l'ID passé en param
            $this->iLicID = $iLicID;

            // Initialise les variables de la classe selon l'ID
            $this->init();
        }

    }

    /**
     * Détruit la connexion à la db
     */
    public function __destruct() {
        $this->oLicMySQL->fClose();

    }

    /**
     * Retourne la valeur souhaitée selon le nom du champ en param
     * @param string $sName -> Nom du champs
     * @return string
     */
    public function __get($sName) {

        // Retourne la valeur souhaitée
        return $this->$sName;

    }

    /**
     * Initalise les variables de la classe avec les données reçuent selon l'ID
     */
    public function init() {

        // Séléctionne la licence selon ID
        $sReqSltLic = 'SELECT *
                        FROM '.self::TABLENAME.'
                        WHERE '.self::$sFieldID.' = "'.$this->iLicID.'"
                        LIMIT 1';

        // Exécute la requête
        $rLic = $this->oLicMySQL->fQuery($sReqSltLic);

        // Met en forme la ressource SQL
        $aLic = $this->oLicMySQL->fFetch($rLic);

        // Assigne aux variables de la class les données reçuent
        $this->sLicProduct       = $aLic[self::$sFieldProduct];
        $this->sLicDesc          = $aLic[self::$sFieldDesc];
        $this->sLicKey           = $aLic[self::$sFieldKey];
        $this->iLicDateAdded     = $aLic[self::$sFieldDateAdded];
        $this->iLicDateEdited    = $aLic[self::$sFieldDateEdited];
        $this->iLicUserAdded     = $aLic[self::$sFieldUserAdded];
        $this->iLicUserEdited    = $aLic[self::$sFieldUserEdited];

    }

    /**
     * Récupère toutes les licences
     * @param ressource SQL $rData -> & indique l'index mémoire de la variable
     * @param string $sArg -> Argument pour la séléction des licences
     * @return \cLicences
     */
    public function getAll(&$rData,$sArg = null) {
        if(empty($rData)) {
            $sReqSltAll = 'SELECT *
                            FROM '.self::TABLENAME.(!empty($sArg) ? ' '.$sArg : null);

            $rData = $this->oLicMySQL->fQuery($sReqSltAll);
        }

        // On met en forme les données
        $aData = $this->oLicMySQL->fFetch($rData); <--- LINE 112

        // Si on a des données
        if(!empty($aData)) {

            // Parcours les données
            while($sValue = $aData) {

                // Retourne un nouvel objet licence
                return new cLicences($sValue[self::$sFieldID]);
            }
        }

    }

}

这是我的页面:

// Affiche les erreurs
error_reporting(E_ALL);

// Change le dossier courant
chdir('../../../');

// Fichier requis pour traitement
require_once('./configuration/general.conf.php');
require_once(PATH_CONFIGURATION.'user.conf.php');
require_once(PATH_CLASS.'mysqli.class.php');
require_once(PATH_MODULES.'licencesManager/langages/'.SITE_LANG.'.lang.php');
require_once(PATH_MODULES.'licencesManager/classes/licences.class.php');

// Nouvelle connexion à la db
$oMySQL = new cMySQLi(DB_USERNAME,DB_PASSWORD,DB_HOSTNAME,DB_HOSTPORT,DB_DATABASE);

// Initialise la classe licence
$oLicences = new cLicences();

// Récupération de toutes les licences
$sReqSelectLicence = "SELECT id_licence
                        FROM t_licences";

$rLicences = $oMySQL->fQuery($sReqSelectLicence);

// Affiche les infos de la licence
while($oLicence = cLicences::getAll($rLicences)) {
    echo '<tr>
            <td>'.$oLicence->iLicID.'</td>
            <td>'.$oLicence->sLicProduct.'</td>
            <td>
                <button onclick="fShowLicence('.$oLicence->iLicID.')" class="btn btn-xs btn-primary">
                    <i class="fa fa-key hidden-xs"></i> '.$_SESSION['mdlLicShow'].'
                </button>
            </td>
            <td><i class="fa fa-pencil"></i> <i class="fa fa-trash-o"></i></td>
        </tr>';
}

// Ferme la connexion à la base de données
$oMySQL->fClose();

这是完整的错误:

致命错误:当不在 /srv/www/htdocs/dev/php/TEST/DAS/iRat-tools/modules/licencesManager/classes/licences.class 的对象上下文中时使用 $this。 php 在第 112 行

我在这个问题上卡住了 3 天。如果有人可以帮助我找到解决方案。

【问题讨论】:

  • 第 112 行在哪里?
  • 基本上,您正在尝试在静态上下文中访问某物的实例。最简单的解决方法是创建对象的 new self 并使用新创建的 self 来访问非静态内容。要么,要么不要混合静态和非静态。
  • 能否在源代码中标出错误所在的行?如果没有标记,每个人都必须弄清楚哪一行可能是 112。
  • 第 112 行进入类 cLicences
  • 我看到了 ahmet2106 的帖子,我尝试用帖子中的解决方案解决我的问题,但它不起作用。如果我提出一个新问题,那是因为我在 Internet 上找不到解决方案

标签: php class this fatal-error


【解决方案1】:

问题来了:

while($oLicence = cLicences::getAll($rLicences)) {

您正在尝试静态访问getAll 方法,而不是在类(对象)的实例上调用它。因此,当您在内部使用 $this 时,您必须在此方法调用中对象上下文。

你应该把它改成调用你已经创建的对象的方法。:

while($oLicence = $cLicences->getAll($rLicences)) {

【讨论】:

  • 感谢您的回答。现在,我有一个新错误:致命错误:在 /srv/www/htdocs/dev/php/TEST/DAS/iRat-tools/modules/licencesManager 中的非对象上调用成员函数 fFetch() /classes/licences.class.php 第 114 行
【解决方案2】:

您正在静态调用 getAll(),因此对象上下文错误:PHP 期望 getAll() 被定义为类 cLicenses 中的静态函数。

在您的页面中,更改此行:

while($oLicence = cLicences::getAll($rLicences)) {

到这里:

while($oLicence = $oLicences->getAll($rLicences)) {

您现在在页面中之前定义的cLicenses 类对象上调用getAll()

【讨论】:

    猜你喜欢
    • 2012-09-25
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    相关资源
    最近更新 更多