Basic PHP problems - php

When I use this function variables created by the included scripts are retained within the scope of this function.
function reqscript($script)
{
$include_dir = 'inc/';
$page_ext = '.php';
include($include_dir.$script.$page_ext);
}
Is there any way of me not having to use the following method?
include(buildfilename('...'));

If you want to define some variables in your included file, you have to use $GLOBALS.
e.g: $foobar = 42; should be $GLOBALS['foobar'] = 42;
So $foobar is available in the global scope (outside of functions).
But I would prefer a buildfilename() method.

Your answer is on php.net already, use return at the end of your included file.
http://php.net/manual/en/function.include.php
Example #5:
return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1
?>

I suggest you adopt your code to use the buildfilename() method, like Floem suggested. However, if you can't or do not wish to do so, here's a simple wrapper to import variables to the global namespace:
class Req {
public function __construct($src) {
include($src);
foreach (get_object_vars($this) as $name => $value) {
$_GLOBALS[$name] = $value;
}
}
}
function reqscript($script) {
$include_dir = 'inc/';
$page_ext = '.php';
new Req($include_dir . $script . $page_ext);
}

Related

How to access PHP variable on every part of a wordpress page? [duplicate]

I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?
The $GLOBALS array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.
// config.php
global $variable;
$variable = 5;
// other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally as
echo $GLOBALS['variable']
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
usage for define (NOTE - without the dollar)
echo HOSTNAME;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
demo |
info
You can declare global variables as static attributes:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function echoFoo() {
echo global::$foo;
}
You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.
Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:
function capital() {
return my_var() . ' is the capital of Italy';
}
function my_var() {
return 'Rome';
}

PHP use variable defined outside of function [duplicate]

I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?
The $GLOBALS array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.
// config.php
global $variable;
$variable = 5;
// other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally as
echo $GLOBALS['variable']
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
usage for define (NOTE - without the dollar)
echo HOSTNAME;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
demo |
info
You can declare global variables as static attributes:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function echoFoo() {
echo global::$foo;
}
You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.
Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:
function capital() {
return my_var() . ' is the capital of Italy';
}
function my_var() {
return 'Rome';
}

How do I get the included elements during include in php?

I'd like to get the class/included variables/elements when I included a php file/class, somehow maybe I should try reflection to do that? If so, how?
For instance, I'd have a PHP class called foo.php:
<?php
class foo
{
public function bar()
{
return "foobar";
}
}
?>
then, in bar.php, I would like to:
<?php
class bar
{
public function foo()
{
$included_resources = include("foo.php"); // Notice, $included_resources is an array
if (($key = array_search("foo", $included_resources)) != false) // "foo" can be any variable or class name
return $included_resources[$key]->bar();
}
}
$helloworld = new bar();
echo $helloworld->foo();
?>
Result: a string value of "foobar" will be represented on the screen
First, store the declared variables in an array before including a file. Then do the include. Then store the declared variables in another array again. Then simply check the difference:
$declared_vars_before = get_defined_vars();
include 'another_file.php';
$declared_vars_after = get_defined_vars();
foreach ($declared_vars_after as $value) {
if (!in_array($value, $defined_vars_before)) {
echo $value . '<br>';
}
}
Same with classes, but use get_declared_classes instead of get_defined_vars.

Access local variable in function from outside function (PHP)

Is there a way to achieve the following in PHP, or is it simply not allowed? (See commented line below)
function outside() {
$variable = 'some value';
inside();
}
function inside() {
// is it possible to access $variable here without passing it as an argument?
}
note that using the global keyword is not advisable, as you have no control (you never know where else in your app the variable is used and altered). but if you are using classes, it'll make things a lot easier!
class myClass {
var $myVar = 'some value';
function inside() {
$this->myVar = 'anothervalue';
$this->outside(); // echoes 'anothervalue'
}
function outside() {
echo $this->myVar; // anothervalue
}
}
Its not possible. If $variable is a global variable you could have access it by global keyword. But this is in a function. So you can not access it.
It can be achieved by setting a global variable by$GLOBALS array though. But again, you are utilizing the global context.
function outside() {
$GLOBALS['variable'] = 'some value';
inside();
}
function inside() {
global $variable;
echo $variable;
}
No, you cannot access the local variable of a function from another function, without passing it as an argument.
You can use global variables for this, but then the variable wouldn't remain local.
It's not possible. You can do it by using global. if you just only do not want to define the parameters but could give it inside the function you can use:
function outside() {
$variable = 'some value';
inside(1,2,3);
}
function inside() {
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
for that see the php manual funct_get_args()
You cannot access the local variable in function. Variable have to set as global
function outside() {
global $variable;
$variable = 'some value';
inside();
}
function inside() {
global $variable;
echo $variable;
}
This works

Inside function variables to be used in includes in PHP

I have a function that includes another file like so
// some function
function SomeFunction()
{
$someData = 'SomeData';
include_once('some_file.php');
}
// some_file.php
<?php echo $someData; ?>
How would I get this to work where the include file can use the variables from the calling function? I will be using some output buffering.
As long as $someData is defined in SomeFunction(), some_file.php will have access to $someData.
If you need access to variables outside of SomeFunction(), pass them as arguments to SomeFunction().
That's already available :)
See include()
The best would be to not do use globals at all, but pass the variable as parameter:
function SomeFunction()
{
$someData = 'SomeData';
include_once('some_file.php');
some_foo($someData);
}
Otherwise you risk transforming your code base in spaghetty code, at least on the long term.
Seems kinda unorganized to include files in functions...what about...
function SomeFunction()
{
$someData = 'SomeData';
return $someData;
}
$data = SomeFunction();
<?php include('file.php') ?> // file.php can now use $data
You don't have to do anything. Usage of include() (and it's siblings) is analogous to copy-pasting the code from the included file into the including file at the spot where include() is called.
Simple example
test.php
<?php
$foo = 'bar';
function test()
{
$bar = 'baz';
include 'test2.php';
}
test();
test2.php
<?php
echo '<pre>', print_r( get_defined_vars(), 1 ), '</pre>';
Again, this is analogous to the combined
<?php
$foo = 'bar';
function test()
{
$bar = 'baz';
echo '<pre>', print_r( get_defined_vars(), 1 ), '</pre>';
}
test();

Categories