Paolo Rossi
Paolo Rossi

Reputation: 2510

PHP call class method to another class

I've 3 class (Mysqliconn, Users and News).

Mysqliconn.class

Class Mysqliconn {
..connect to db
}

News.class

class News {
private $db;

   public function __construct( Mysqliconn $db ) {

   $this->db = $db; 
   }

   public test() {
     do something... 
   }
 }

Users.class

class Users {
private $db;

   public function __construct( Mysqliconn $db ) {

   $this->db = $db; 
   }

   public test2() {

     do something...
   }
}

In my php page

 $db = new Mysqliconn();
 $nw = new News( $db );
 $us = new Users( $db )

 $us->test2();
 $nw->test();

My error

Catchable fatal error: Argument 1 
passed to Users::__construct() must be an instance of Mysqliconn, 
none given, called in ....\class\class.news.php 

Now in my class Users I would like to to call a News class method, but I get an error if I try to istantiate the class News inside class Users.

How can I do this? Thanks.

Upvotes: 0

Views: 133

Answers (1)

Sid
Sid

Reputation: 856

Plz post what error you are getting. Otherwise it's difficult to capture the problem. But if you dont want to instantiate the news class in the user class you can access it like

class News
{
    // news class
}

class Users
{
    public function some_method(News $news){
        // work with the $news object
    }
}

$us = new Users();
$us->some_method(new News(/*$db*/));

This is just a basic code to give you an idea of how you can use it. In a production environment you have to take a lot of precautions.

Upvotes: 1

Related Questions