3

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

2
  • 1
    Did you instanciate your class ? You can use self::sanitizeFieldRows($par1,$par2,$par3) if you are in static mode. Commented Jul 28, 2015 at 7:57
  • ^ Thanks for this also @Vincent Decaux, learned something today. Commented Jul 28, 2015 at 8:10

1 Answer 1

2

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

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

1 Comment

OH RIGHT! I forgot about that, Wonder why I'm calling as :: instead of creating the $field = new Field thing. Silly me.

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.