简体   繁体   中英

PHP Class Reference to Parent Variable

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM