I am new to OOP PHP and I have been working with the procedural API since I started web development, so it is difficult for me to migrate to OOP.
so let's say I have four files .phpand structures below.
connection.db.php
<?php
define("DB_HOST", "127.0.0.1");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "sample_db");
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo (!$db->connect_error) ? NULL : die("<pre>Unable to connect to the MySQL Server -> $db->connect_error</pre>");
?>
sampleclass.class.php
<?php
public $db;
class MySQLqueries {
public function samplefunction($queryString) {
$sqlQry = mysqli->query($queryString);
return ($sqlQry) ? "<pre>Query Executed Successfully</pre>" : die("<pre>An error occured -> $db->error</pre>");
}
}
?>
includes.inc.php
<?php
error_reporting(0);
date_default_timezone_set("Asia/Manila");
require 'connection.db.php';
require 'sampleclass.class.php';
?>
index.php
<?php
require 'includes.inc.php';
$todo = new MySQLqueries;
echo $todo->samplefunction("SELECT `sample_column` FROM `sample_table` WHERE `sample_column` = 'sample_value';");
?>
As you may or may not have noticed, my problem is how to use $dbfrom connection.db.phpin samplefunctionfromsampleclass.class.php
You can ask me why not create a method __construct()in sampleclass.class.php and just move "$ db = new mysqli (DB_HOST, DB_USER, DB_PASS, DB_NAME)"; there?. well, if I do this, all other classes should have their own constructorand $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);declared there correctly?
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); connection.db.php , .
, public $db; sampleclass.class.php, , . - , .
PS: Google Ph.D. , , , OOP PHP-MySQLi Programming, .