How to Pass a variable into an include file? - php

I have use
include ('base.php')
script in my other scripts ( more.php). Now base.php should receive one variable from more.php. How to pass a variable from more.php into base.php?

If you include a script file A into a script file B, then A has the same global variable scope as B has:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope. — include manual page
So if you define a variable in A, then you have access to that variable in B:
// A.php
$varInA = 'foobar';
include 'B.php';
// B.php
echo $varInA;

Create a function within base.php, like so:
function setup($config) {
// Do something with config
}
and call it from more.php..
setup($somevar);
Or, you could try using classes and member variables and constructors.

Related

Why `require` and `use` can not be written in the function body?

file1:
<?php
function done() {
require_once '/home/vendor/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
#omitted
}
?>
file2
<?php
require_once '/home/vendor/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
function done() {
#omitted
}
?>
Why file1 can't work?
It should be rewritten as file2, why require and use can be written in the function body?
because from php doc
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
for use keyword the same rules apply
In Your case declaring isìnside the function limit the visibilty scope of the vars and code declaread in the included file

PHP - Accessing variables in an included script from an included script

I have a list of files that I require_once at the beginning of my main scripts.
In one of those files, I have a bunch of functions.
In another one of those files, I have a bunch of constants (which are variables at the moment, but they are essentially constants).
Main.php
require_once \Constants.php
require_once \Functions.php
From within main.php, I am able to call functions and call the constants from their respective scripts... I am also able to call functions and pass the constants from Constants.php as parameters to the functions.
However, I am not able to use functions that have the constants embedded within them.
In other words, I cannot use the functions from Functions.php that already have the variables from the Constants.php file within the functions, but I am able to use functions from Functions.php if they do not have any variables from other included files within the function.
Function FirstFunction(){ echo $Constant1; return 1 }
FirstFunction() uses $Constant1 from Constants.php and does not work.
Function SecondFunction($param){ echo $param; return 1 }
SecondFunction() can be passed $Constant1 from Constants.php as a parameter and it works fine.
Questions:
Is there a way for me be able to use my Main.php to call a function file and a constant file and have the function file use variables from the constant file without explicitly calling or passing them from within Main.php?
If I were to daisy chain them (Main.php calls Functions.php; Functions.php calls Constants.php) will this work? (I kind of tried this but not well enough to either trust or rule out this method just yet).
Note
Most of the information I am able to find is regarding using variables from included files, but not specifically about included files using variables from other included files.
This sounds like a simple scope issue, that has nothing to do with your include-cycle.
When you create your 'constants' as normal PHP-variables ($name='value';), in the root scope of the Constants.php, then they must be called inside any later functions, by referencing them first ... like this:
$name='value';
/** other stuff **/
function Foo(){
global $name;
//You have access to $name here
}
The true solution tho, is to actually define your constants as real constants, which makes them available in any scope ... like this:
define('NAME','value');
/** other stuff **/
function Foo(){
//You immediately have access to NAME here
}
Only downside to true constants is, that they are constant ... meaning, they can’t be changed at a later point in your script.
You can read more about 'scope' here: http://php.net/manual/en/language.variables.scope.php
include() works as if the contents of the file being included are literally cut/paste into the spot where the include() call is:
variables.php:
<?php
$foo = 'bar';
test.php:
<?php
var_dump($foo); // notice: undefined variable
include('variables.php');
var_dump($foo); // string(3) "bar"
Note that standard PHP variable scoping rules apply. So if you do the include() inside a function:
<?php
var_dump($foo); // notice: undefined variable
function test() {
var_dump($foo); // notice: undefined variable
include('variables.php');
var_dump($foo); // string(3) "bar"
}
test(); // call the test function
var_dump($foo); // notice: undefined variable
notice how $foo doesn't exist before/after the function is defined/called - it will only exist WITHIN the function, and only AFTER it's been included().
If you want your standard variables to be truly global, you'll have to include the file at a global scope, or declare them global:
variables.php:
<?php
global $foo;
$foo = 'bar';
and then using the same script, $foo will "magically" appear for the final var_dump, because it's been made global.

How do I get the path to script calling a method in another script?

How do I get the path to a script that is calling a method of a class defined in another script, from within the class?
That is, I'd like to make a call to a class method - defined in b.php - from a.php as:
PHP code
# a.php
require 'b.php';
$obj = new AsyncDecorator('ClassName');
$obj->Call('methodName');
... with, as previously mentioned, the class being defined in b.php similarly to this snippet:
PHP code
# b.php
class AsyncDecorator
{
public function Call($method)
{
# Currently equals to b.php - I need it to be 'a.php'
$require = __FILE__;
}
}
That is, I need to know that the calling script was a.php, and I need to do it dynamically. If I'm creating and using the AsyncDecorator class in c.php, then $require should equal to 'c.php'.
A possible solution to this problem is making either the Call() method, or the initialization of the decorator to accept a $file_path parameter in which __FILE__ is passed:
PHP code
$obj = new AsyncDecorator('ClassName', __FILE__);
$obj->Call('methodName');
This has the minor downside of requiring the file path to be passed each time this object is created, which might add unnecessary parameters and not keep its use as simple and seamless as possible.
There is a gist here with a function to get the calling class.

Pass PHP variable from page to class to page

I have a question regarding scope in PHP
I have set a variable in one file. That file creates an instance of a class and then calls a method of that class. This method includes a separate file. What I need to know is how can the variable in the first page be referenced in the second page without having to pass it as a constructor variable to the class.
For example:
page_1.php
<?php
$variable = "my variable";
$myClass = new MyClass();
$myClass->loadPage();
?>
MyClass.php
<?php
Class MyClass
{
public function loadPage ()
{
include_once('page_2.php');
}
}
?>
page_2.php
<?php
echo $variable;
?>
I hear that using a Global scope is frowned upon, and I am sure it is not the right thing to do to place the variable as fields in the class, especially considering there will likely be several unrelated variables in file_1.php which will need to be referenced in page_2.php. So what do I need to do?
Thanks
Pass the variable as a parameter to loadPage():
$myClass->loadPage($variable);
and update the definition of loadPage() to accept a parameter:
public function loadPage ($variable)
When you include page_2.php you are simply inserting the code in that script into the currently-running script and scope. As a result, the code in page_2.php can simply reference $variable without any extra work.
Keep in mind that the same scoping rules apply here as elsewhere, so if you define a class or enclosure in page_2.php, you will have to explicitly pass $variable into those scopes to access its value.

Variable accessibility with require_once/ob_start()

Maybe I'm just tired or just am simply confused, but I'm having a strange issue dealing with some require_once() calls and ob_start().
Basic Structure:
Top of Main.php:
require_once 'config.php'; // includes variable $A = "bar", and Function "foo"
function getPage(){
ob_start();
include 'some_file.php';
$html = ob_get_clean();
echo $html;
die();
}
getPage();
some_file.php
require_once 'config.php'; // includes same config file
var_dump($A); // NULL
foo(); // runs, returns correct value
Config.php
$A = 'bar';
function foo(){
return "FOO";
}
So, what is wrong here? I'm including a file while buffering output. The required file config.php holds a variable and function. When including some_file.php during the buffer, the variable $A is apparently NOT set/accessible. The function foo CAN execute.
The documentation says:
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
Your provided code does not illustrate the problem that you're describing. When I run it as-is, it correctly shows that the variable is defined.
That being said, the thing to remember is that what looks like a global variable in an included file actually ends up in the scope of the function that's calling it. So if the first time require_once() is called is from a function, the $A variable is scoped to the function - and disappears when the function returns, just like any other variable defined inside the function.
If you absolutely must define a global variable inside an included file (are you sure? really?), make sure you only include that file from the global scope - not from within a function. If you need to access the variable from within a function, include the file outside the function, and then use the global keyword to access the variable from within the function.

Categories