1

We are trying to understand the best way to use mysqli/other classes in multiple custom classes so that we don't instantiate a new object every time.

Is the code below the best/correct way of doing this?

The functions are only examples.

Thank you :)

<?php class Base { public function __get($name) { if($name == 'db'){ $db = new mysqli('**', '*s', '*', '*'); $this->db = $db; return $db; } if($name == 'blowfish'){ $blowfish = new PasswordHash(8, true); $this->blowfish = $blowfish; return $blowfish; } } } class A extends Base { public function validate($username, $password) { $query = $this->db->query("SELECT * FROM users"); return $query->num_rows; } public function password($password) { return $this->blowfish->HashPassword($password); } } class PasswordHash { public function __construct($iteration_count_log2, $portable_hashes) { } public function HashPassword($password) { return $password; } } $a = new A; echo $a->validate('test','test'); // returns number rows count as expected echo $a->password('password123'); // returns password123 as expected ?> 

1 Answer 1

1

You are/should probably be more interested in Dependency Injection instead of creating a tight coupling of Base|A and the MySQL database.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.