1

In an effort to keep my code clean, I am attempting to replace a whole bunch of code in my constructor with a function. I believe I am calling the function correctly but i'm not able to assign values to the variables as intended.

public function __construct($docID) {

    self::getDocumentInfo($docID);
    self::getTranscriptionInfo($docID);

}

private static function getTranscriptionInfo($docID) {
    $this->documentTranscription = 5;
}

Im getting an error "PHP Fatal error: Using $this when not in object context in ...". This is simplified for postings purpose, but would it be better just have a very large constructor and skip the functions all together? Or is their a better way to assign values?

1
  • you should change your $this to self:: Commented Jan 7, 2016 at 7:11

1 Answer 1

3

A static method is not a part of the class instance. The static keyword means the method can be called within your class but it won't have any of the instance variables.

Remove the static keyword and change this:

self::getDocumentInfo($docID);
self::getTranscriptionInfo($docID);

to this:

$this->getDocumentInfo($docID);
$this->getTranscriptionInfo($docID);

Using $this means it will be calling it within the right instance context.

Some info the static keyword (added emphasis in italics):

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).

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.

Source

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

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

1 Comment

Ok, that is very understandable. Thank you!

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.