Is it possible to pass an object into the constructor of a PHP class, and set that object as a global variable that can be used by the rest of the functions in the class?
For example:
class test {
function __construct($arg1, $arg2, $arg3) {
global $DB, $ode, $sel;
$DB = arg1;
$ode = arg2;
$sel = $arg3;
}
function query(){
$DB->query(...);
}
}
When I try to do this, I get a "Call to a member function on a non-object" error. Is there anyway to do this? Otherwise, I have to pass the objects into each individual function directly.
Thanks!
You probably want to assign them to values on $this
.
In your constructor, you'd do:
$this->DB = $arg1;
Then in your query function:
$this->DB->query(...);
This should similarly be done with the other arguments to your constructor.
$this
in an instance context is how you reference the current instance. There's also keywords parent::
and self::
to access members of the superclass and static members of the class, respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With