As the title says there is a problem accessing variable (associative array) inside class from included file. Here is the source code both class and include file:
require("applications/cw_database.php");
require("config/dbConfig.php");
require("config/appConfig.php");
class APP_ASSESMENTS
{
private $dbObj;
private $DisplayOutput = "";
public function __construct($PageParams)
{
try
{
$dbObj = new CW_DB($dbConfig['hostname'],$dbConfig['username'],$dbConfig['password'],$dbConfig['name'],$dbConfig['port']);
} catch (Exception $e) {
throw new ErrorException($e);
}
}
...
The other part has nothing to do with $dbConfig.
Also this is the included file (config/dbConfig.php):
/*
Testing configuration for MySQL database
*/
$dbConfig['username'] = "phpcoursework"; // changed on demand
$dbConfig['password'] = "phpcoursework"; // changed on demand
$dbConfig['hostname'] = "localhost"; // changed on demand
$dbConfig['name'] = "students"; // changed on demand
$dbConfig['port'] = 3306; // default for MySQL
First,
$dbObjwill not automatically assume class member scope, it will create a local copy ofCW_DBand discard it when__constructreturns. You need to explicitly reference the property;Anyway, global state using
globalas suggested by others will “work“, but if you’re using OOP practices you’re best not to do that. You can actually return from aninclude(), so an option would be to do the following:And inject it into the object, via constructor or method (here’s constructor)
It would be recommended that you go another level up: instead, inject the database object itself, taking the dependency out of your
APP_ASSESSMENTSclass.(Also, PascalCase is the typical convention of class naming, such as
AppAssessmentsandCwDb)This simple change allows you to remove the dependency from
AppAssessmentsonCwDb. That way, if you extendCwDbfor some reason, you can just pass in an instance of the extended class without having to change any code inAppAssessmentsYou can change the
AppAssessmentsconstructor like so:This takes advantage of PHPs (limited, albeit still useful) type-hinting, ensuring the first argument is always of the correct type.
This plays into part of the open/closed principle: classes should be open to extension but closed for modification.