在不使用静态方法的情况下不在对象上下文中使用 $this [英] Using $this when not in object context without the use of static methods

查看:39
本文介绍了在不使用静态方法的情况下不在对象上下文中使用 $this的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试手动解密我自己的云文件以进行测试,但我不太了解 PHP 语言.

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

我面临的问题是:

PHP 致命错误:不在对象上下文中使用 $this

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

我环顾四周,但我发现的只是错误地将 $this 与静态方法一起使用.但是,我正在编辑的文件中没有任何静态方法.

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.

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

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

script.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

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?

推荐答案

您不能在静态调用中使用 $this.因为$this 是指当前对象,并且您还没有为类Crypt 创建任何对象.

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

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

Also you haven't declared decryptedPrivateKey method as static.

您可以通过两种方式调用类方法.您可以使用Tom Wright 的建议方式

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

(1) 用对象调用

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

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

a) 您应该将方法定义为静态.

a) You should define method as static.

b) 您应该使用 self 关键字 并调用另一个静态方法,

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
}

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

所以你有两个选择:-

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

i) Either declare parseHeader method also static OR

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

希望对你有帮助:-)

这篇关于在不使用静态方法的情况下不在对象上下文中使用 $this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆