1

I'm wondering why the following lines causes an error. doSomething() gets called from another PHP file.

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

2 Answers 2

4

How are you calling the method?

Doing

MyClass::doSomething('[email protected]');

will fail, as it's not a static method, and you're not accessing a static variable.

However, doing

$obj = new MyClass();
$obj->doSomething('[email protected]');

should work.

Sign up to request clarification or add additional context in comments.

Comments

1

To use your class and method which are not static, you must instanciate your class :

$object = new MyClass();
$object->doSomething('[email protected]');

You cannot call your non-static method statically, like this :
MyClass::doSomething('[email protected]');

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
  • And, as your statically-called non-static method is using $this : Fatal error: Using $this when not in object context

For more informations, you should read the [**Classes and Objects**][1] section of the manual -- and, for this specific question, its [**Static Keyword**][2] page.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.