PHP - Reverse of calling a function? - php

Having some trouble with this..
<?php
EG204_ExoSkel();
function EG204_ExoSkel() {
$to_be_end = 'Red';
everything_loop();
}
function everything_loop() {
echo $to_be_end;
}
?>
The code above will not echo Red, so I must be trying to use functions backwards. Might that be possible?
All that is in the Everything function is to be apart of different foreach loops.

Try this one (send it as an argument)
<?php
EG204_ExoSkel();
function EG204_ExoSkel() {
$to_be_end = 'Red';
everything_loop($to_be_end);
}
function everything_loop($argument) {
echo $argument;
}
?>
http://sandbox.phpcode.eu/g/3c1b6.php

You have scoping issues. The declaration of $to_be_end is only available in the EG204_ExoSkel function.
If you want to use it outside that function you should use global to make it globally available. And also add global in the other function (also to made use of the global variable). Resulting in this:
EG204_ExoSkel();
function EG204_ExoSkel() {
global $to_be_end;
$to_be_end = 'Red';
everything_loop();
}
function everything_loop() {
global $to_be_end;
echo $to_be_end;
}
Note: using global is considered bad practice and tends to make a mess of your code (and even introduce hard to find bugs). A better solution (if possible in your real code) is to pass on the variable to the other function(s).

Try referencing $to_be_end as a global!
WARNING Global are bad practice Avoid
<?php
EG204_ExoSkel();
function EG204_ExoSkel() {
global $to_be_end;
$to_be_end = 'Red';
everything_loop();
}
function everything_loop() {
global $to_be_end;
echo $to_be_end;
}
?>

Related

How to call a global dynamic variable in php

I try to find the solution since many hours, but I can't solve it (I'm not a programmer ;)).
On a function, I have set a dynamic array which I want to use in another function.
To do this, I thought to use $GLOBALS[] array
I have no problem to call the variable out of the function one, but when I try to use it in function 2, it doesn't works.
Here is my code :
function one($name,$a,$b,$c)
{
// $GLOBALS[${$name}] = array($a,$b,$c);
global $$name;
$$name = array($a,$b,$c);
}
function two($name)
{
$name="D1";
echo ${$name}[1];
}
one("D1",10,20,30);
one("D2",100,200,300);
two("D1"); // doesn't works
$name="D1";
echo ${$name}[1]; // works, gives 20
$name="D2";
echo ${$name}[1]; // works, gives 200
It doesn't works and I do not understand why.
Thanks for your help.
Etienne
how about doing something like this:
function one() {
$dynamicArray = generateDynamicArray();
return $dynamicArray;
}
function two() {
$one = one(); // if it's in a class use: $this->one();
foreach($one in $key=>$value) {
// your code for each item in the array we got form function one()
}
}
instead of defining it globally.
<?php
function one($name,$a,$b,$c)
{
global $$name;
$$name = array($a,$b,$c);
}
function two($name)
{
global $$name;
echo ${$name}[0];
}
one("D1",10,20,30);
two("D1");
The scope of your function is different to the global scope.

What is the best way to acces language variables in a function?

Basically, I've included my language file in my page, in that language file are arrays like $lang['ERROR']['TITLE'], so my question is: what is the best way to acces those variables in functions?
You could use one of two methods depending on what you want:
1) Declare a global variable:
<?php
$GLOBALS['lang'] = $lang;
function test () {
echo $GLOBALS['lang']['ERROR']['TITLE'];
}
test();
?>
This makes it able to be used inside any function.
2) Pass it to the function:
function test ($var) {
echo $var;
}
test ($lang['ERROR']['TITLE']);
This only allows for it inside the one specific function.
You can try something like this:
<?php
$lang = ...;
function test () {
global $lang;
echo $lang['ERROR']['TITLE'];
}
test();
?>
The global-keyword is needed, to tell php that it should look for this variable in the global-scope. Otherwise, $lang is undefined.
You need to use the global keyword at the top of your function to access a variable defined outside the function. Eg:
function test() {
global $lang;
echo $lang['ERROR']['TITLE'];
}

Create and use global variable without the 'global' keyword?

As of now I create a variable like this in a file that's loaded on all pages:
<?php
add_action( 'parse_query', 'my_global_vars' );
function my_global_vars() {
/* CUSTOM GLOBAL VARIABLES */
$variable_name = get_query_var('category_name');
}
?>
And every time I want to use it (in other files), I must do it like this:
<?php
global $variable_name;
if( $variable_name = 'news' ){
// Do something
}
?>
And when I need to use the variable multiple times in the same file, I add global $variable_name; at the top of the file, and simply use $variable_name in rest of the instances.
But as the number of variables increase, I find it harder to manage the list of global $variable_names at the top of all files.
Is there a way to define a variable as global at the time of creation and simply use $variable_name everywhere else?
EDIT: One way is to define variable like this:
<?php
add_action( 'parse_query', 'my_global_vars' );
function my_global_vars() {
/* CUSTOM GLOBAL VARIABLES */
global $variable_name;
$variable_name = get_query_var('category_name');
}
?>
And use it like using $GLOBALS[] like this $GLOBALS['variable_name'] elsewhere.
Having a lot of global vars is usually bad. It becomes a mess very quickly.
If you really need global variables the best approach is to use static class variables. They are just as global as the others, but they enforce better naming and pre-declaration so the end result is somewhat better.
If you really need normal global vars you can also use the $GLOBALS variable, it is available in every scope and is basically an array of all the global variables.
global $variable_name;
do_something_with($variable_name);
is the same as
do_something_with($GLOBALS['variable_name']);
You can use a static class for this and keep it OOP:
<?php
class GlobalVariables {
private static $vars = array();
public static function get($name, $default = null) {
return (isset(self::$vars[$name]) ? self::$vars[$name] : $default);
}
public static function set($name, $value) {
self::$vars[$name] = $value;
}
}
function foo() {
GlobalVariables::set('foo', 'oof');
}
function bar() {
var_dump( GlobalVariables::get('foo') );
}
foo();
bar(); //oof
?>
DEMO
Alternatively, you can use a Singleton pattern:
<?php
class GlobalVariables {
private static $instance;
private $vars = array();
public static function get() {
if (empty(self::$instance)) {
self::$instance = new GlobalVariables();
}
return self::$instance;
}
public function __get($name) {
return (isset($this->vars[$name]) ? $this->vars[$name] : null);
}
public function __set($name, $value) {
$this->vars[$name] = $value;
}
}
function foo() {
GlobalVariables::get()->foo = 'oof';
}
function bar() {
var_dump( GlobalVariables::get()->foo );
}
foo();
bar(); //oof
?>
DEMO.
Use whichever you find most readable.
GlobalVariables::set('key', 'value');
GlobalVariables::get('key');
or
GlobalVariables::get()->key = 'value';
GlobalVariables::get()->key;
Completely alternatively, if you hate dynamicness, simply use static variables (this, however, requires you to create all variables beforehand):
<?php
class GlobalVariables {
public static $foo;
}
GlobalVariables::$foo = 'oof';
var_dump( GlobalVariables::$foo );
?>
Using global outside a function doesn't do anything. It's meant for inside functions. You can simply remove your global statements.
Edit: I suggest that you try to reduce the number of global variables you have by structuring them. Group them into arrays or objects. E.g., instead of user_name, user_id, user_is_admin, prefer user['name'], user['id'], user['is_admin'], then you only have one variable (user) to declare as global instead of three.

php function not getting include

I have this in index.php
require('include\inc\config.inc');
When I created a function which require some variable from config.inc
When I run, it says the variable is missing
I need to redeclare the config.inc else the function will never work.
Is there a way to work around?
Now I have this
function test(){
require('include\inc\config.inc');
echo $tmp;
}
instead of
require('include\inc\config.inc');
function test(){
echo $tmp;
}
You should read about the variable scope. The $tmp variable is global and is not visible inside any function, unless declared with global
require('include\inc\config.inc');
function test(){
global $tmp;
echo $tmp;
}
Your variable is out of scope in the test() function as previously mentioned and using globals is not considered good practice. You need to pass the variable $tmp into the function test() like this:-
function test($tmp)
{
echo $tmp;
}
Then call the function like this:-
require_once 'include/inc/configure.inc'
test($tmp);
I'm not fluent in PHP, but can't you write:
require('include\inc\config.inc');
function test() use ($tmp) {
echo $tmp;
}

Global variable in PHP is not working

I need to access $layers from inside the function isOk($layer), but everything i tried the outside function variable $layers is ok, but inside the function, even with global is return null.
Here is the code:
$layers = array();
foreach($pcb['PcbFile'] as $file){
if(!empty($file['layer'])){
$layers[$file['layer']] = 'ok';
}
}
// Prints OK!
var_dump($layers);
function isOk($layer){
global $layers;
// Not OK! prints NULL
var_dump($layers);
if(array_key_exists($layer, $layers))
return ' ok';
return '';
}
// NOT OK
echo isOk('MD');
I always use Object orientation, but this was something so simple that i made with a simple function... Why $layers is not being 'received' correcly inside the function?
Watch this...
HalfAssedFramework.php
<?php
class HalfAssedFramework {
public static function run($path) {
include $path;
}
}
HalfAssedFramework::run('example.php');
example.php
<?php
$layers = array();
foreach($pcb['PcbFile'] as $file){
if(!empty($file['layer'])){
$layers[$file['layer']] = 'ok';
}
}
// Prints OK!
var_dump($layers);
function isOk($layer){
global $layers;
// Not OK! prints NULL
var_dump($layers);
if(array_key_exists($layer, $layers))
return ' ok';
return '';
}
// NOT OK
echo isOk('MD');
Run example.php directly, and it should work. Run HalfAssedFramework.php, and it won't.
The problem is scope. When example.php is included inside the run function, all the code inside it inherits the function's scope. In that scope, $layers isn't global by default.
To fix this, you have a couple of options:
If you know example.php will never run directly, you can say global $layers; at the beginning of the file. I'm not sure whether this will work if the script is run directly, though.
Replace $layers with $GLOBALS['layers'] everywhere.
Add $layers as an argument to isOk.
Put this code within a class, as suggested by Geoffrey.
Not exactly answering the question, but have you considered not using globals? Globals really aren't that cool: they make your code harder to read, harder to understand and as a consequence, harder to maintain.
Consider something like that:
<?php
class LayerCollection
{
private $layers;
public function __construct($layers)
{
$this->layers = $layers;
}
public static function fromPcbFile($data)
{
$layers = array();
foreach ($data['PcbFile'] as $layer) {
if (!empty($layer)) {
$layers[$layer] = true;
}
}
return new self($layers);
}
public function hasLayer($layer)
{
return array_key_exists($layer, $this->layers);
}
}
$layers = LayerCollection::fromPcbFile($pcb);
var_dump($layers->hasLayer('MD'));
Doesn't it look better? You can then proceed to enrich LayerCollection as you need more ways of interacting with your layers. This is not perfect, since there's still a static method lying around (makes testing harder, a factory would be better suited for that job), but that's a good start for a refactoring.
More about why globals are evil: https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil

Categories