Brian Coolidge
Brian Coolidge

Reputation: 4649

Using $this when not in object context calling method inside class

I have this line of code that calls a method of buildField from a class name called Field

$field_dictionary[$key] = Field::buildField($key, $request);

In Field class here is my buildField method

public function buildField($key, $request) {

    $field_vocabulary = [];

    $image = $_FILES[$key];
    $image['tmp_name']['image'] = true;
    // Calling this another method from same class
    $field = $this->sanitizeFieldRows($image['tmp_name'], $request->post($key . '_name'), $request->post($key . '_description'));

    $field_vocabulary['name'] = implode('|', $field->field_1);
    $field_vocabulary['description'] = implode('|', $field->field_2);
    $field_vocabulary['image'] = implode('|', $field->reference);

    return $field_vocabulary;
}

In that code, there's a this line

$field = $this->sanitizeFieldRows($image['tmp_name'], $request->post($key . '_name'), $request->post($key . '_description'));

I'm calling another method from the same class. It does some function I just removed since it's so long.

public function sanitizeFieldRows($reference, $field_1, $field_2 = null) {

    // Some code etc.....
    // Outputs an object
    return (object) $output;
}

But the thing is, I'm calling $this->sanitizeFieldRows($par1,$par2,$par3) but it prompts an error saying:

Using $this when not in object context in

But when I did Field::sanitizeFieldRows($par1,$par2,$par3) it works, but these method is in the same object yet it's not the static method that I'm calling.

Anything wrong with this?

Here's the same questions:

Using $this when not in object context?

Using $this when not in object context

Using $this when not in object context

PHP using $this when not in object context

Fatal error: Using $this when not in object context

Fatal error: Using $this when not in object context explanation?

Using $this when not in object context php

Upvotes: 3

Views: 2154

Answers (1)

William J.
William J.

Reputation: 1584

Since buildField is a static method the $this variable is not available in its scope.

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

http://php.net/manual/en/language.oop5.static.php

Upvotes: 2

Related Questions