I haven't touched PHP in a couple months and don't have access to any of my previous projects for reference. Essentially, I have my file lib.php
which instantiates all objects, creates all vars/functions that will be accessed throughout most of the application. This file, lib.php
is then called into the header.php file, viarequire_once
. Within lib, I have a function which creates the MySQL PDO connection
try {
$server = array(
'server' => 'localhost:3306',
'database' => 'to_do_list',
'user' => 'root',
'password' => '',
);
$link = new PDO('mysql:host='.$server['server'].';dbname='.$server['database'].'',$server['user'],$server['password']);
$link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
echo "Error Could not connect to database";
exit;
}
I want the variables within here, such as $link
to be accessible in all class files which are instantiated within lib.php. How would I go about doing this in the most efficient way?
<?php
// Session Start
session_start();
// Link Database
// Link var created here I want to be accessible in any classes instantiated below
try {
$server = array(
'server' => 'localhost:3306',
'database' => 'to_do_list',
'user' => 'root',
'password' => '',
);
$link = new PDO('mysql:host='.$server['server'].';dbname='.$server['database'].'',$server['user'],$server['password']);
$link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
echo "Error Could not connect to database";
exit;
}
// Functions
// Action GET/POST/SET
function getAction()
{
if(isset($_POST['action']))
{
$action = $_POST['action'];
} else if(isset($_GET['action'])) {
$action = $_GET['action'];
} else {
echo "GET/SET/POST action master failed";
}
return $action;
}
// Input GET/POST/SET
function inputReturn($inputName) {
if(isset($_POST[$inputName])) {
$inputVal = $_POST[$inputName];
} else if (isset($_GET[$inputName])) {
$inputVal = $_GET[$inputName];
} else {
$inputVal = "";
echo "GET/SET/POST input master failed";
}
return $inputVal;
}
// Require classes
require_once("user.php");
// Instantiate classes
$instUser = new user;
?>