Michael Tichoň
Michael Tichoň

Reputation: 291

PHP OOP declaring class into class

I have 2 classes and I would like to have 1 more for comfort :)

So I have class for database and system. I would like to have 3rd classs for functions. This class MUST use functions from database since there are SQL Queries. This is What I ended with:

class database {
   public function __construct() {

      $this->mysqli = new mysqli('localhost', 'root', '', 'roids');
      $this->func = new functions();
        }
}

class functions {

    function __construct(){
        $db = new database();
    }

    public function banned() {
        $q = $db->select($this->prefix."banned", "*", "banned_ip", $this->getIP());

        if (0 == 0) {
            header('Location: banned.php'); // For testing
        }

    }
}

And I this kind of version ends in cycle. Any solutions ? Thanks a lot

Upvotes: 0

Views: 74

Answers (1)

sybear
sybear

Reputation: 7784

Some of your classes must be a source, so other classes may use instances of it.

Let me show you one example:

class DataBase { //THIS class is a source.
  public $mysqli ;

  public function __construct(){
    $this->mysqli = new mysqli('localhost', 'root', '', 'roids');
    $this->mysqli->set_charset("utf-8") ;
  }

  public function ready(){
    return ($this->mysqli instanceof MySQLi && $this->mysqli->ping()) ;
  }
}

class User {
  protected $db;
  public function __construct(DataBase $db){
    $this->db = $db ; //Now you can use your source
  }

  public function isBanned(){
    if ($this->db->ready()){
      $result = $this->db->mysqli->query("SELECT id FROM banned WHERE name='Hacker' ; ") ;
      return ($result && $result->num_rows >= 1) ;
    }
    return false ;
  }
}

Then instantiate the source and give it to instance of User:

$database = new DataBase() ;
$user = new User($database) ;

Now you can use a more complexed function:

if ($user->isBanned()) exit("You are banned") ;

The same way you can make class Functions and use it (other classes may use it) as a source.

Upvotes: 1

Related Questions