Ashish Patil Ashish Patil - 6 months ago 21
PHP Question

Using $this when not in object context without the use of static methods

I'm trying to manually decrypt my owncloud's files to test it, but I don't know the PHP language well.

The problem I'm facing is:


PHP Fatal Error: Using $this when not in object context


I looked around for some time, but all I came across was using
$this
wrongly along with static methods. But, there aren't any static methods in the files I'm editing.

There's a file
'script.php'
where I'm calling another file's
(crypt.php)
methods.

script.php:

<?php
namespace OCA\Files_Encryption\Crypto;
use OCA\Files_Encryption\Crypto\Crypt;
require_once 'crypt.php';

.
.
.

$decryptedUserKey = Crypt::decryptPrivateKey($encryptedUserKey, $userPassword);

.
.
.


Here's the other crypt.php file, where the fatal error occurs
crypt.php

<?php
namespace OCA\Files_Encryption\Crypto;

class Crypt {

.
.
.

public function decryptedPrivateKey($privateKey, $password = '', $uid = '') {
$header = $this->parseHeader($privateKey);
.
.
.
}

}


The last line of code throws the fatal error. Any ideas?

Answer

You can not use $this in static call. Because $this is refer current object and you haven't created any object for class Crypt.

Also you haven't declared decryptedPrivateKey method as static.

You can call class method by two ways. You can use Tom Wright's suggested way

(1) Call with object

$crypt = new Crypt(); // create class object
$decryptedUserKey = $crypt->decryptPrivateKey($encryptedUserKey, $userPassword); // call class method via object 

OR

(2) Call without object (static call)

a) You should define method as static.

b) You should use self keyword and call another static method,

public static function decryptedPrivateKey($privateKey, $password = '', $uid = '') {
    $header = self::parseHeader($privateKey);
}

public static function parseHeader() { // static parseHeader
  // stuff
}

In above case, parseHeader method must be static as well.

So you have two options:-

i) Either declare parseHeader method also static OR

ii) create object of current class and call non static method parseHeader

public static function decryptedPrivateKey($privateKey, $password = '', $uid = '') {
     $obj = new self(); // create object of current class
     $header = $obj->parseHeader($privateKey); // call method via object
}

public function parseHeader() { // Non static parseHeader
  // stuff
}

Hope it will help you :-)