0

I want to create a class for a license manager , however , I have to use another class to do what I need is to create a new connection to the database in the __construct class .

When I try to use a function , getAll in this case , I have a PHP error that appears on the screen :

Fatal error: Using $ this WHEN NOT in object context in [...] line 112 .

Here is my class :

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

    }

}

Here is my page:

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

Here is the full error:

Fatal error: Using $this when not in object context in /srv/www/htdocs/dev/php/TEST/DAS/iRat-tools/modules/licencesManager/classes/licences.class.php on line 112

I 'm stuck on this problem for 3 days now. If anyone can help me to find a solution.

SatanicGeek
  • 342
  • 5
  • 15
  • Where is line number 112? – Rizier123 Jun 30 '15 at 07:54
  • You're trying to access an instance of something in a static context, basically. The easiest workaround would be to create a `new self` of the object and use that newly created self to access non-static stuff. Either that or don't mix static and non-static. – Andrei Jun 30 '15 at 07:55
  • Could you mark the line with the error in the source code? Without a mark everybody has to figure out which line could be 112. – Frank Martin Jun 30 '15 at 07:58
  • Line 112 into the class cLicences – SatanicGeek Jun 30 '15 at 08:39
  • I saw the post by **ahmet2106** and I try to fix my problem with the solution in the post but it doesn't work. If I ask a new question, it's because I can't find a solution in Internet – SatanicGeek Jun 30 '15 at 08:43

2 Answers2

1

You are calling getAll() statically, hence the object context error: PHP is expecting getAll() to be defined as a static function within class cLicenses.

In your page, change this line:

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

To this:

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

You're now calling getAll() on cLicenses class object defined earlier on in your page.

RuubW
  • 556
  • 4
  • 17
1

Here's the problem:

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

You're trying to access getAll method statically instead of calling it on an instance of the class (object). Therefore you have to object context in this method call, while you're using $this inside.

You should just change it to call method on object that you have already created anyway.:

while($oLicence = $cLicences->getAll($rLicences)) {
Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64
  • Thank you for the answer. Now, I have a new error : **Fatal error: Call to a member function fFetch() on a non-object in /srv/www/htdocs/dev/php/TEST/DAS/iRat-tools/modules/licencesManager/classes/licences.class.php on line 114** – SatanicGeek Jun 30 '15 at 08:40