0

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.

6
  • 2
    What error? Class doesn't exist? Have you included the class file? Commented Feb 28, 2013 at 13:07
  • 3
    why don't you inject your News class in your User constructor? Commented Feb 28, 2013 at 13:08
  • Users doesn't make sense. How do you have a single Users? Commented Feb 28, 2013 at 13:09
  • yes it does, if it is a static class Commented Feb 28, 2013 at 13:10
  • Why do you pass the $db as a parameter? I would create a singleton class for the Database class. Commented Feb 28, 2013 at 13:11

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It's a bad idea. Your code doesn't even work. And it's not a singleton either.
still not a singleton: remove function instance() and calls it dependency injection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.