I have this index.php file
# Loading configurations.
loadConfiguration('database');
loadConfiguration('site');
# Initializing the database connection.
$db = new database($c['db']['host'], $c['db']['username'], $c['db']['password'], $c['db']['name']);
unset($c['db']['password']);
And loadConfiguration() is set as follow:
function loadConfiguration($string) { require(path.'config/'.$string.'.con.php'); }
I checked that database.con.php and site.con.php are into the config/ folder.
And the only error i get is a Notice: Undefined variable: c in the following line
$db = new database($c['db']['host'], $c['db']['username'], $c['db']['password'], $c['db']['name']);
Here's the database.con.php
# Ignore.
if (!defined('APP_ON')) { die('Feel the rain...'); }
$c['db']['host'] = 'localhost';
$c['db']['username'] = 'root';
$c['db']['password'] = '';
$c['db']['name'] = 'name';
Here's the site.con.php
# Ignore.
if (!defined('APP_ON')) { die('Feel the rain...'); }
/* Site informations */
$c['site']['name'] = 'Namek';
$c['site']['mail'] = 'mail#whocares.com';
$c['site']['enable-email'] = false;
$c['site']['debug-mode'] = true;
What am i doing wrong?
The required code is executed within the function, so $c is a local variable and not accessible in global scope.
You may either use some fancy design pattern to make $c global (e.g. use a Registry (R::$c, R::get('c'), an Environment ($this->env->c), ...) or you could change your configuration loader function to return the name of the file and require outside of it:
require_once configFile('database');
function configFile($name) {
return path . 'config/' . $name . '.con.php';
}
Please don't use global variable according security purpose. you can set your variable in registry variable and then access it.
Related
I have a static variable like so to keep track of some operations in memory without using a real database
<?php
class Database
{
public static $database = array();
}
When I try to access the database from another php file like so
<?php
include 'database.php';
function createPaymentRef($username, $password, $amount)
{
$finalResult = array();
$ref = generateTimedTransactionRef($username, $password, $amount);
global $requestData;
global $ip;
Database::$database->unset($username); //Expected type 'object'. Found 'array'.intelephense(1006) error
$requestData->ip = $ip;
$requestData->reference = $ref;
$finalResult['result'] = $ref;
return $finalResult;
}
?>
I am get an error saying
Expected type 'object'. Found 'array'.intelephense(1006)
How can I resolve this?
-> is used to access properties or methods of an object. Database::$database is an array, not an object. The syntax to unset an array element is
unset($array[$index])
so it should be
unset(Database:$database[$username]);
Check if the static variable exists and if the array element in it exists, then unset using unset(Database::$database[$username]):
$db = Database::$database;
if($username && $db && isset($db[$username])){
unset(Database::$database[$username]);
}
I want to access a method from an external class, within another file.
I have an external class, let's say:
external/file.php
class ExternalClass {
private $myClient;
const CONSTANT = 'some/path';
public function _constructor($myClient) {
$this->myClient = $myClient;
}
public function getSome($information) { // Need to access this function
$data = new StdObject();
$data->information = $information;
$result = $this->myClient->post(
self::CONSTANT,
$data
);
return($result['code'] == 200 ? json_decode($result['body']) : false);
}
public static function instance($SETTINGS) {
return new ExternalClass(new MyClient($SETTINGS['externalclass']['host']));
}
}
... I would like to reference this class in another file.
internal/file.php
include_once('external/file.php');
$externalClassInstance = ExternalClass::instance($SETTINGS); // line 3
$externalClass = new ExternalClass(); // line 4
$externalClassGetSome = $externalClass->getSome($information); // line 5
The problem is, I'm not sure if I'm correctly referencing the external methods inside the internal file.
Is "Line 3" even necessary?
Also, the addition of Line 5 code breaks any code after it.
Firstly I don't know why you would need line 3.
Secondly you seem to have the answer right there
include_once('external/file.php');
$externalClass = new ExternalClass(); // line 4
$externalClassGetSome = $externalClass->getSome($information);
try to change from
include_once('external/file.php');
to
include_once('../external/file.php');
becauase its in external directory and your file is in internal directory.
Perhaps I'm going about this the wrong way, but I have a Configuration file that I'm trying to pass through a parameter, the reason I'm doing this is because I'm experimenting with what I call a ("Core"/"Client") structure, probably not the correct name, but basically whatever I edit on the "Core" is updated to all of the "Client" subdomains, which will respectively call code such as
include '/path/to/core/index.php';
generateIndex($Param, $Param);
So, Basically, here's what I have, on the "Clients" side I have a Configuration file, called "Configuration.php" this holds all of the static variables pertaining to the Clients database. Example below:
<?php
$SQL_HOST = "";
$SQL_DATBASE = "";
$SQL_ACCOUNT_TABLE = "";
$SQL_DATA_TABLE = "";
$SQL_REWARDS_TABLE = "";
$SQL_USERNAME = "";
$SQL_PASSWORD = "";
?>
So, Basically, I'm trying to do this,
generateIndex($SQLConnection, $Configuration);
However, It's not allowing me to do so and presenting me with this error.
Notice: Undefined variable: Configuration in /opt/lampp/htdocs/client/index.php on line 16
Respectively, Line 16 is the line above containing "generateIndex"
Now, on the "Core" side what I'm trying to do is the following to get data.
function generateIndex($SQLConnection, $SQLConfig) {
...
$SQLConfig->TBL_NAME
...
}
Which I don't know if it throws an error yet, because I can't pass $Configuation to the function.
Your can user return context for get variable from file.
As example:
File db_config.php:
<?php
return array(
'NAME' => 'foo_bar',
'USER' => 'qwerty',
'PASS' => '12345',
// Any parameters
);
You another file with include configuration:
<?php
// Code here...
$dbConfig = include 'db_config';
// Code here
If file have a return statement, then your can get this values with = operator and include file.
Read the file before putting it in the function.
generateIndex($SQLConnection, file("configuration.php"));
file 1:
function test() {
global $Configuration;
echo $Configuration
}
file 2 (perhaps config)
$Configuration = "Hi!";
I am writing a MVC Framework (for the purpose of learning and discovery as opposed to actually intending to use it) and I have came across a slight problem.
I have a config.php file:
$route['default'] = 'home';
$db['host'] = 'localhost';
$db['name'] = 'db-name';
$db['user'] = 'user-name';
$db['pass'] = 'user-pass';
$enc_key = 'enc_key'
I load these via a static method in my boot class:
public static function getConfig($type) {
/**
* static getConfig method gets configuration data from the config file
*
* #param string $type - variable to return from the config file.
* #return string|bool|array - the specified element from the config file, or FALSE on failure
*/
if (require_once \BASE . 'config.php') {
if (isset(${$type})) {
return ${$type};
} else {
throw new \Exception("Variable '{$type}' is undefined in " . \BASE . "config.php");
return FALSE;
}
} else {
throw new \Exception("Can not load config file at: " . \BASE . 'config.php');
return FALSE;
}
}
and then load the route like so:
public function routeURI($uri) {
...
$route = $this::getConfig('route');
...
}
which catches the exception:
"Variable 'route' is undefined in skeleton/config.php"
now, it works fine if I make the config.php file like so
$config['route']['default'] = 'home'
...
and change the two lines in the method like so:
if (isset($config[$type])) {
return $config[$type];
I have also tried using $$type instead of ${$type} with the same problem.
Is there something I am overlooking?
As written, this function can be called only once, because it uses require_once and on subsequent calls you won't bring in the local variables defined in config.php anymore. I suspect you are getting this error on your second call to getConfig().
i'd like to set up some global variables for storing several things.
i've tried it like this:
function init_web()
{
$webname = "myweb";
$web['webname'] = $webname;
$web['server_root'] = $_SERVER['DOCUMENT_ROOT']."/$webname/";
$web['lang']="en";
}
the problem is that i can't access those variables inside of functions ..
i've tried using global $web; but didnt help.
what's the trick to get it global?
thanks
While you'll get the usual "global variables are bad" crying, here's the basics:
$web = array(); // define the var at the "top level" of the code tree, outside any functions/classes.
function init_web() {
global $web; // make it visible in the function
$web['lang'] = 'en'; // make some settings
}
basically, you had it, but hadn't defined the variable outside the function. Just saying 'global' within the function won't magically create one outside the function - it already has to exist before you try to "internalize" it to the function and change/access its contents.
You are on the right track:
$web = array();
function init_web()
{
global $web;
$webname = "myweb";
$web['webname'] = $webname;
$web['server_root'] = $_SERVER['DOCUMENT_ROOT']."/$webname/";
$web['lang']="en";
}
You can define them constant
define('WEBNAME',"myweb");
and can use everywhere in your application because constant are global in nature by default.
and this is the way to store constant as constant as they never changed dynamically until you move to new server or change configuration.
you can use session variables:
session_start(); // at the top of the php page
function init_web()
{
$webname = "myweb";
$_SESSION['webname'] = $webname;
$_SESSION['server_root'] = $_SERVER['DOCUMENT_ROOT']."/$webname/";
$_SESSION['lang']="en";
}
now they can be 'globally' accessable :-)
Declare $web outside the function and reference it inside with the $GLOBALS superglobal:
// Declare in global scope
$web = array();
function init_web()
{
$webname = "myweb";
// Access via superglobal in function scope
$GLOBALS['web']['webname'] = $webname;
$GLOBALS['web']['server_root'] = $_SERVER['DOCUMENT_ROOT']."/$webname/";
$GLOBALS['web']['lang']="en";
}
If you're just storing scalar values (strings, ints, floats - not arrays, objects), you should use define().
This will make your configurations global and constant.
As to answer your question,
First define your variables outside the scope of that function (perhaps in a config file) and then use the global keyword to make it global when you need them.