0

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

2
  • 1
    "This class MUST use functions from database since there are SQL Queries" --- it's not sufficient actually. Prefer delegation over inheritance. And inherit only if your classes are related by "is a" preposition. Commented Feb 17, 2013 at 20:57
  • You should not have a functions class. You can have a "user". You can have a "database". But you cannot have a "functions". Commented Feb 18, 2013 at 3:29

1 Answer 1

1

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.

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

Comments

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.