L
L
lexstile2018-04-14 21:36:21
PHP
lexstile, 2018-04-14 21:36:21

How to call a method of another class inside a method of one class in php?

There are classes:

class DataBase{
  public function name1(){
    //
  }
}
class User(){
  public function name2(){
    // Здесь нужно вызвать метод name1() из класса DataBase
  }
}

I try:
protected $db;
    public function __constructor(DataBase $DB)
    {
        $this->db = $DB;
    }
  public function name2(){
    $this->db->name1();
  }

Error:
Call to a member function name1() on null in...
Only works if I initialize the class inside the name2() method.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maksim Fedorov, 2018-04-14
@lexstile

https://ideone.com/yQMST1

P
profesor08, 2018-04-14
@profesor08

It says to you: Call to a member function name1() on null , which means that the $this->db field has the value $this->db . $this->db , for you, the value from the $DB parameter is initialized in the class constructor . This means that $DB is also null . And now think about why null is passed to your class instead of an object of the DataBase class .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question