1

I'm building an API service and have a parent class:

classAPI {
    public responseCode = "";
    public responseMessageLog ="";
    function run{
        // here I call my user auth class
        $oUser = new classUser(...);
    }
}

Inside my classUser I do a bunch of stuff and then write a bunch of variables: responseMessageLog (which is running log of where the script went) and responseCode (which is set to 0 or 1 or whatever depending on success or failure or warning).

I need to access my responseCode and responseMessageLog variables from within my User class and my parent API class, but I don't really want to be passing these variables into each child class and then passing them back. I would like it that when I update the variable in the child class it updates everywhere in all my class.... kind of like a global variable would... but I know that's not a good idea.

How have others stopped passing variables down the rabbit trail of classes.

in this class I

1 Answer 1

1

Passing dependencies isn't a rabbit hole you want to avoid--it makes for more testable code. However, you don't need to pass every property, you can pass the parent object.

In your case just pass the classAPI object into the constructor of the classUser and in the constructor assign it to property. The classAPI properties are public so you can access them in an instance of classUser.

 ClassAPI {
     public $responseCode = "";
     public $responseMessageLog ="";

     public function run{
         // here I call my user auth class
         $oUser = new ClassUser($this, ...);
      }
  }

 ClassUser {
     public $myClassApi = null;

     public function __construct(ClassAPI $myClassApi) {

         $this->myClassApi = $myClassApi;
      }

     public function someFunction() {
         echo $this->myClassApi->responseCode;
     }

   }

Added notes:

  • In case it comes up in another answer, don't use static properties to do what you're trying to do.
  • Capitalize your class names.
  • In production code I might add an initialization function in ClasUser instead passing the ClassAPI directly into the constructor.
Sign up to request clarification or add additional context in comments.

4 Comments

can I call methods like this as well?
@NathanLeggatt if they're public visibility (not private or protected)
doesn't appear to see my methods that are in the parent class
@Nathan parent class? Not sure what you mean, no child classes your example. Using my example, if you had a function foo() in ClassAPI you'd be able to call from the someFunction() method of the ClassUser with $this->myClassApi->foo() assuming foo() is public.

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.