Passing objects to PHP constructor error

Is it possible to pass an object to the constructor of a PHP class and set this object as a global variable that can be used by other functions of the class?

For instance:

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 the error "Member function call on non-object." Is there any way to do this? Otherwise, I have to pass the objects to each individual function directly.

Thank!

+3
source share
4 answers

You probably want to assign their values ​​to $this.

In your constructor, you would do:

$this->DB = $arg1;

Then in your query function:

$this->DB->query(...);

This should also be done with other arguments for your constructor.

$this . parent:: self:: .

+6

...
, , - . :

<?php
class test {
    // Declaring the variables.
    // (Or "members", as they are known in OOP terms)
    private $DB;
    protected $ode;
    public $sel;

    function __construct($arg1, $arg2, $arg3) {
      $this->DB = arg1;
      $this->ode = arg2;
      $this->sel = $arg3;
    }

    function query(){
      $this->DB->query(...);
    }
}
?>

private, protected public . PHP: .

+2

let's say you have a db object

$db = new db();

and another object:

$object = new object($db);

class object{

    //passing $db to constructor
    function object($db){

       //assign it to $this
       $this-db = $db;

    }

     //using it later
    function somefunction(){

        $sql = "SELECT * FROM table";

        $this->db->query($sql);

    }

}
+2
source

you can do this quite easily by storing the argument as a property of the object:

function __construct($arg1, $arg2, $arg3) {
   $this->db = arg1;
}

function f()
{
  $this->db->query(...);
}
+1
source

Source: https://habr.com/ru/post/1728800/


All Articles