I am new to OOP PHP, and I've been working with procedural API since I've started Web Development so I'm having a hard time migrating to OOP.
so let's say I have this four .php file and 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 have not noticed, my problem is how to use the $db from connection.db.php in the samplefunction of sampleclass.class.php
You may ask me, why not create a __construct() method in sampleclass.class.php and just move the "$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);" there ?. well if I'm to do this, all other classes will have to have it's own constructor and $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); declared there right?
With $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); on the connection.db.php I assume that I can reuse it versatile-ly.
You see I've declared a public $db; in sampleclass.class.php but I don't know what's next. If someone can help me dearly, then I would be a lot grateful.
PS: I've already consulted Dr. Google Ph.D. regarding this matter, and I only got tons of articles or video tutorials showing how to use and do OOP PHP-MySQLi Programming but without using classes and methods.