简体   繁体   English

在PHP中访问类变量

[英]Accessing class variables in PHP

I'm wondering why the following lines causes an error. 我想知道为什么以下几行会导致错误。 doSomething() gets called from another PHP file. 从另一个PHP文件调用doSomething()

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
    }
}

How are you calling the method? 您如何调用该方法?

Doing 在做

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

will fail, as it's not a static method, and you're not accessing a static variable. 将失败,因为它不是静态方法,并且您没有访问静态变量。

However, doing 但是,这样做

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

should work. 应该管用。

To use your class and method which are not static , you must instanciate your class : 要使用非static类和方法,必须实例化类:

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


You cannot call your non-static method statically, like this : 您不能像这样静态地调用非静态方法:

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

Calling this will get you : 调用此命令将使您:

  • A warning (I'm using PHP 5.3) : Strict standards: Non-static method MyClass::doSomething() should not be called statically 警告(我使用的是PHP 5.3)Strict standards: Non-static method MyClass::doSomething() should not be called statically
  • And, as your statically-called non-static method is using $this : Fatal error: Using $this when not in object context 而且,由于您的静态调用非静态方法正在使用$thisFatal error: Using $this when not in object context


For more informations, you should read the Classes and Objects section of the manual -- and, for this specific question, its Static Keyword page. 有关更多信息,您应该阅读手册的“ 类和对象”部分-对于此特定问题,请阅读其“ 静态关键字”页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM