不在对象上下文中时使用 $this? PHP

Using $this when not in object context? PHP

我在 PHP 中有一个 class。在构造函数中,我为 属性 定义了一个值,然后我必须在一个方法中访问它。但是,我不断得到 Fatal error: Using $this when not in object context。我需要从 class.

中访问 属性
class Base {
    public $vat;
    public function __construct() {
        $settingsClass = new GeneralSettings();
        $generalSettings = $settingsClass->getSettings();
        $this->vat = $generalSettings['vat'];
    }
    public function vatPrice($price) {
        $vatPrice = $price + (($this->vat / 100) * $price);
        return self::formatPrice($vatPrice);
    }
}

我用一个简单的值测试了你的 class,没有发现任何错误。

class Base {
    public $vat;
    public function __construct() {
        $this->vat = 75;
    }
    public function vatPrice($price) {
        $vatPrice = $price + (($this->vat / 100) * $price);
        return self::formatPrice($vatPrice);
    }

    public static function formatPrice($price) {
        echo $price;
    }
}

$myClass = new Base();
$myClass->vatPrice(100);

请注意 formatPrice 是一个静态函数。


  1. 有时你想引用class的一个实例的某些属性,只针对一个对象,所以在这种情况下你必须定义一个visibility $bar形式的属性或方法;对于变量或 visibility function bar($args...),您可以使用 $this 访问,因为 $this 是 class(当前对象)的实际实例的引用。
  2. 也许您想在某些属性中为所有人获得相同的值 class 的实例,即:静态 attribute/method。在这种情况下,您必须为变量定义 visibility static $bar 或为函数定义 visibility function $bar($args...),您可以使用 self 关键字访问它们。

可见性为 public、受保护或私有

当您遇到类似情况时:

class Foo {
    ...
    public static function bar() { ... }
    ...
}

bar()函数调用如下:

  • 在 Foo 之外:self::bar();
  • Foo 内部:Foo::bar();

相反,如果你有这样的事情:

class Foo {
    ...
    public function bar () { ... }
    ...
}

然后,

  • 在 Foo 之外:

您必须首先实例化 class,然后从该对象访问 bar():

$myObject = new Foo();
$myObject->bar();
  • Foo: $this->bar();
  • 内部

请参阅 PHP 文档中的 static keyword 参考。