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();
Related
I want to create an array which is in my function.php code definded so I do not have to transfer the array through my hole code. But it won't work...
This is an example of my function.php:
<?php
define("titleArray", array());
function foo(){
echo $this->titleArray;
}
function boo(){
array_push($this->titleArray, "Hello");
}
But it doesn't work... How can I fix that so that every function has access to the array?
Greetings
I suggest that you store your array globally using the $GLOBALS, and instead of using echo to print an array, use the print_r method instead.
<?php
$GLOBALS["titleArray"] = array('world');
function foo(){
print_r($GLOBALS["titleArray"]);
}
function boo(){
array_push($GLOBALS["titleArray"], "Hello");
print_r($GLOBALS["titleArray"]);
}
foo();
boo();
just remove $this
<?php
define("titleArray", array());
function foo(){
echo titleArray;
}
function boo(){
array_push(titleArray, "Hello");
}
note that array values are allowed after php 7.0 version
Generally we use define to make constant value which never updates, use class instead
<?php
class abc {
$titleArray = [];
function foo(){
echo $this->titleArray;
}
function boo(){
array_push($this->titleArray, "Hello");
}
}
The define() function defines a constant. Constants are much like variables, except for the following differences: A constant's value cannot be changed after it is set.
There are two ways to do it:
use global in every function
declare $GLOBALS[] once outside the function
$titleArray = [];
// $GLOBALS['titleArray'] = [];
function foo(){
global $titleArray;
print_r($titleArray);
// print_r($GLOBALS['titleArray']);
}
function boo(){
global $titleArray;
array_push($this->titleArray, "Hello");
// array_push($GLOBALS['titleArray'], "Hello");
}
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.
Get array declared outside function to every function without passing argument in php
<?php
$arr2= array('00','12','23','73');
function f1() {
print_r($arr2);
}
f1();
?>
Here we can pass the array f1($arr2), but I want to know whether we acess array inside the function 'f1' without passing, something like setting global or some else ?
I want only to know, whether it is possible or not ?
use global:
function f1() {
global $arr2;
print_r($arr2);
}
However, as #steven already point out, it is considered bad practice.
These thread talk about why global variable is considered bad:
Are global variables in PHP considered bad practice? If so, why?
PHP global in functions
It's possible using globals however it is typically considered a bad practice.
Example from php.net:
<?php
function test() {
$foo = "local variable";
echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
echo '$foo in current scope: ' . $foo . "\n";
}
$foo = "Example content";
test();
?>
Use global $arr2:
<?php
$arr2= array('00','12','23','73');
function f1()
{
global $arr2;
print_r($arr2);
}
f1();
?>
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);
}
i have alias to include() in my functions.php file:
function render_template($template)
{
include($template);
}
and simple template.html :
Hello, <?php echo $name ?>
But unfortunately, alias function gave me this output:
require 'functions.php';
$name = "world";
include('template.html'); // Hello, world
render_template('template.html'); // PHP Notice:Undefined variable: name
why is that? and how i can fix this?
thanks.
You have two more options to make it work around the scope issue. (Using global would require localising a long list of vars. Also it's not actually clear if your $name resides in the global scope anyway and always.)
First you could just turn your render_template() function into a name-resolver:
function template($t) {
return $t; // maybe add a directory later on
}
Using it like this:
$name = "world";
include(template('template.html'));
Which is nicer to read and has obvious syntactical meaning.
The more quirky alternative is capturing the local variables for render_template:
$name = "world";
render_template('template.html', get_defined_vars());
Where render_template would require this addition:
function render_template($template, $vars)
{
extract($vars); // in lieu of global $var1,$var2,$var3,...
include($template);
}
So that's more cumbersome than using a name-resolver.
The variable $name is not visible at the point where include is called (inside function render_template). One way to fix it would be:
function render_template($template)
{
global $name;
include($template);
}
Its a Scope Problem, you can set the variable to global, or encapsulate the whole thing a little bit more, for example like that:
class view{
private $_data;
public function __construct(){
$this->_data = new stdClass();
}
public function __get($name){
return $this->_data->{$name};
}
public function __set($name,$value){
$this->_data->{$name} = $value;
}
public function render($template){
$data = $this->_data;
include($template);
}
}
$view = new view;
$view->name = "world";
$view->render('template.html');
template.html :
Hello <?php print $data->name; ?>
If $name is in the global scope then you can get around it by declaring the variable global with the function. But a better solution would be to re-architect the code to require passing the relevant variable value into the function.
This is expected.
Look here.
You would be interested in the following quote, "If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs".