在不使用静态方法的情况下不在对象上下文中使用 $this

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

我正在尝试手动解密我自己的云文件来测试它,但我不太了解 PHP 语言。

我面临的问题是:

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

我环顾四周,但我所遇到的只是错误地使用 $this 和静态方法。但是,我正在编辑的文件中没有任何静态方法。

有一个文件 'script.php',我在其中调用另一个文件的 (crypt.php) 方法。

script.php:

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

.
.
.

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

.
.
.

这是另一个 crypt.php 文件,发生致命错误的地方 crypt.php

<?php
namespace OCA\Files_Encryption\Crypto;

class Crypt {

.
.
.

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

}

最后一行代码抛出致命错误。有什么想法吗?

您可能没有将 decryptPrivateKey 定义为 static,但这就是您使用它的方式。

当它实际上不是实例化对象的一部分时,它会继续使用 $this

尝试在 script.php

中使用它
$crypt = new Crypt();
$decryptedUserKey = $crypt->decryptPrivateKey($encryptedUserKey, $userPassword);

您不能在静态调用中使用$this。因为 $this 是参考 current object 而你还没有为 class Crypt 创建任何对象。

您还没有将 decryptedPrivateKey 方法声明为 static.

您可以通过两种方式调用class方法。您可以使用 建议的方式

(1) 用对象调用

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

(2) 无对象调用(静态调用)

a) 你应该将方法定义为静态的。

b) 你应该使用 self keyword 并调用另一个静态方法,

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

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

在上述情况下,parseHeader 方法也必须是静态的。

所以你有两个选择:-

i) 要么声明 parseHeader 方法也是静态的,要么

ii) 创建当前对象class并调用非静态方法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
}

希望对您有所帮助:-)