在PHP中访问类变量


Accessing class variables in PHP

我想知道为什么以下几行会导致错误。doSomething()从另一个PHP文件调用。

class MyClass
{   
    private $word;
    public function __construct()
    {
        $this->word='snuffy';
    }   
    public function doSomething($email)
    {
        echo('word:');
        echo($this->word); //ERROR: Using $this when not in object context
    }
}

如何调用该方法?

MyClass::doSomething('user@example.com');

将会失败,因为它不是一个静态方法,并且您没有访问一个静态变量。

然而,

$obj = new MyClass();
$obj->doSomething('user@xample.com');

要使用非static的类和方法,必须实例化您的类:

$object = new MyClass();
$object->doSomething('test@example.com');


你不能静态地调用你的非静态方法,像这样:

MyClass::doSomething('test@example.com');

调用这个会得到:

  • 一个警告(我使用PHP 5.3): Strict standards: Non-static method MyClass::doSomething() should not be called statically
  • 并且,由于您的静态调用非静态方法使用$this: Fatal error: Using $this when not in object context


要了解更多信息,您应该阅读手册的类和对象一节——对于这个特定的问题,请阅读其静态关键字页面。