How to work with $GLOBALS - php

I have 2 different php files, and in one of the file I created a global array
$GLOBALS['system'] = array(
'mysqli' => array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'database'
)
);
How can I be able to use this array in another file e.g.
$GLOBALS['system']['mysql']['host'];

$GLOBALS['system'] = array();
This is unnecessary. Just do
$system = array();
Now, you can use $system anywhere you want (in other includes, etc), but the catch is that functions won't see it due to scope. That means that each function doesn't have access to $system because it's not in the global scope (and that's a good thing because what if you needed to use $system inside a function?) Now, you can always fall back to
function foo() {
echo $GLOBALS['system'];
}
But that's clunky and it relies on $system being defined somewhere and not changing. So let's inject it instead
function foo($system) {
echo $system;
}
foo($system);

Related

How to store array variable returned from another file?

I've a PHP Configuration File in TYPO3 like
<?php
return array(
'DB' => array(
'database' => 'vicous',
'extTablesDefinitionScript' => 'extTables.php',
'host' => 'localhost',
'password' => '',
'socket' => '',
'username' => 'root',
)
);
?>
I want to get this array on an external php file. How to get that?
Something like this.
function getArray("filepath"){
$variable = filepath return that array
}
My requirement is to get array inside $variable
include and require behave exactly like you want:
$variable = include 'path/to/file.php';
From the docs:
It is possible to execute a return statement inside an included file
in order to terminate processing in that file and return to the script
which called it. Also, it's possible to return values from included
files. You can take the value of the include call as you would for a
normal function.
You Could use like
function getArray($path){
return $variable = require_once( $path );
}

Declare Multiple DB Host in an array and make DB calls

I'm new to PHP. What I'm trying to achieve is declare multiple DB hosts in an array. Something like below mentioned :
$slaves=array(
array( //Slave 1
'name' => 'slave1',
'server' => '10.10.1.10',
'user' => 'user1',
'password' => 'p#ssuser1'
'port' => '3306'),
array( //Slave 2
'name' => 'slave2',
'server' => '10.10.1.11',
'user' => 'user2',
'password' => 'p#ssuser2'
'port' => '3306'),
)
Once done, I want to make random calls to these slaves i.e., every read request should get served from one of the slaves.
$idx = time() % count($slaves);
$slave = $slaves[$idx];
$con = mysqli_connect($slave['server'], $slave['user'], $slave['password'], "dbname");
But this is not working. If I try to connect these slaves individually, it is working. But not when I declare that in an array. Is there a simple way to make random calls to these slaves ? Please highlight where is the mistake in my code. I have checked few links on web but they use functions and this keyword to make DB calls.
If you require any more information, do let me know.
Thanks in advance.
$slave = $slaves[array_rand($slaves)];
$con = mysqli_connect($slave['server'], $slave['user'], $slave['password'], "dbname");
You should use array_rand function to get random value from array. Check it with this modification.
And you forget to pass database name to connect function.

Initialize an Associative Array with Key Names but Empty Values

I cannot find any examples, in books or on the web, describing how one would properly initialize an associative array by name only (with empty values) - unless, of course, this IS the proper way(?)
It just feels as though there is another more efficient way to do this:
config.php
class config {
public static $database = array (
'dbdriver' => '',
'dbhost' => '',
'dbname' => '',
'dbuser' => '',
'dbpass' => ''
);
}
// Is this the right way to initialize an Associative Array with blank values?
// I know it works fine, but it just seems ... longer than necessary.
index.php
require config.php
config::$database['dbdriver'] = 'mysql';
config::$database['dbhost'] = 'localhost';
config::$database['dbname'] = 'test_database';
config::$database['dbuser'] = 'testing';
config::$database['dbpass'] = 'P#$$w0rd';
// This code is irrelevant, only to show that the above array NEEDS to have Key
// names, but Values that will be filled in by a user via a form, or whatever.
Any recommendations, suggestions, or direction would be appreciated. Thanks.
What you have is the most clear option.
But you could shorten it using array_fill_keys, like this:
$database = array_fill_keys(
array('dbdriver', 'dbhost', 'dbname', 'dbuser', 'dbpass'), '');
But if the user has to fill the values anyway, you can just leave the array empty, and just provide the example code in index.php. The keys will automatically be added when you assign a value.
First file:
class config {
public static $database = array();
}
Other file:
config::$database = array(
'driver' => 'mysql',
'dbhost' => 'localhost',
'dbname' => 'test_database',
'dbuser' => 'testing',
'dbpass' => 'P#$$w0rd'
);

Is it possible to define an anonymous function in class scope?

I'd like to assign anonymous functions to arrays in PHP inside of a class, but I keep stumbling over syntax errors.
class Stuff {
private $_preference_defaults = array(
'cookie' => true,
'session' => true,
'database' => true,
'filter' => function($input) { return true; },
'sanitizer' => function($input) { return $input; },
);
};
Will throw an unexpected T_FUNCTION syntax error, and it doesn't matter whether or not the array is static. I got desperate and tried the "old" way of doing it:
class Stuff {
private $_preference_defaults = array(
'cookie' => true,
'session' => true,
'database' => true,
'filter' => create_function('$input', 'return true;'),
'sanitizer' => create_function('$input', 'return $input;'),
);
};
And this led to an unexpected '(', expecting ')' syntax error. However, if I define the functions ahead of time, it does work:
class Stuff {
function _preference_default_filter($input) {
return true;
}
function _preference_default_sanitizer($input) {
return true;
}
private $_preference_defaults = array(
'cookie' => true,
'session' => true,
'database' => true,
'filter' => _preference_default_filter,
'sanitizer' => _preference_default_sanitizer,
);
};
And then I'm able to call those functions within a class method:
function do_stuff($foo) {
return $this->{$this->_preference_defaults['filter']}($foo);
}
Not only is this syntactically sour, in my head it wreaks of poor style and I can imagine this sort of trickery causing headaches in the future.
Am I not able to create an anonymous function at class (static) scope? (I'm thinking maybe because a valid Closure object cannot be created in that context?)
Is there a more... PHP... means to the same end? That is to say, is there a "better" way of assigning trivial default callbacks to array values in class scope? The final snippet I provided gets the job done for sure, but I'd prefer a solution that won't leave me asking the optometrist for a stronger prescription.
Am I not able to create an anonymous function at class (static) scope? (I'm thinking maybe because a valid Closure object cannot be created in that context?)
Yes, because the initial values of class attributes should be known in parsing step, while function call and anonymous function require runtime
Also see here to get the additional details: https://stackoverflow.com/a/9029556/251311
And cannot get your second question :-S
This indeed will not work. During the, lets say, declaration phase you can generally not do much fancy things.
However.. because your properties are just private, and not static.. simply declare everything in the constructor. Problem solved!
This syntax:
'sanitizer' => _preference_default_sanitizer,
Is really bad.. With E_NOTICE on you will actually find it coverts _preference_default_sanitizer to a string first, which is why this may work.
Just set the method name as string.
class Stuff {
private $_preference_defaults = array(
'cookie' => true,
'session' => true,
'database' => true,
'filter' => '_preference_default_filter',
'sanitizer' => '_preference_default_sanitizer',
);
function _preference_default_filter($input) {
return true;
}
function _preference_default_sanitizer($input) {
return true;
}
};
And then call by:
function do_stuff($foo) {
return $this->{$this->_preference_defaults['filter']}($foo);
}
Or
function do_stuff($foo) {
return call_user_func(array($this, $this->_preference_defaults['filter']), $foo);
}

How to get array information

I got configuration file database.php
<?php defined('_ENGINE') or die('Access Denied'); return array (
'adapter' => 'mysqli',
'params' =>
array (
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'db',
'charset' => 'UTF8',
'adapterNamespace' => 'Zend_Db_Adapter',
),
'isDefaultTableAdapter' => true,
'tablePrefix' => 'engine4_',
'tableAdapterClass' => 'Engine_Db_Table',
); ?>
How to get only password from this array?
something like echo $array['password'];
How do I get the array from database.php?
You'll need to include the file and bind the returned value to a variable, such as in the below example.
$db_conf = require ('/path/to/database.php');
$db_conf will contain the data returned by database.php.
Documentation
PHP: include - Manual
How do I read the specific value from my array?
Since you are working with a nested array the solution is not as far away as you might think. First use $a[key] to get to the array stored under params, and then get the value of password from there.
As in the below example.
$password = $array['params']['password'];
Note: The above is, in a logical sense, equivalent to;
$params = $array['params'];
$password = $params['password'];
Documentation
PHP: Arrays - Manual
I tried the above but it's just shouting "Access Denied" in my face, why?
To protect database.php from unintended access it has been protected with a check to see so that it's being used inside of the engine.
The script will die if _ENGINE is not defined.
If you want to use database.php in a script outside of the thought of engine you'll need to define the _ENGINE constant before includeing the file.
define ('_ENGINE', 1);
...
$db_conf = include ('database.php');
echo $array['params']['password'];
Give this a try. :-)

Categories