PHP using variable in an included function - php

Main File;
$opid=$_GET['opid'];
include("etc.php");
etc.php;
function getTierOne() { ... }
I can use $opid variable before or after function but i can't use it in function, it returns undefined.
What should i do to use it with a function in an included file?

$getTierOne = function() use ($opid) {
var_dump($opid);
};

Its because the function only has local scope. It can only see variables defined within the function itself. Any variable defined outside the function can only be imported into the function or used globally.
There are several ways to do this, one of which is the global keyword:
$someVariable = 'someValue';
function getText(){
global $someVariable;
echo $someVariable;
return;
}
getText();
However, I'd advise against this approach. What would happen if you changed $someVariable to another name? You'd have to go to each function you've imported it into and change it as well. Not very dynamic.
The other approach would be this:
$someVariable = 'someValue';
function getText($paramater1){
return $parameter1;
}
echo getText($someVariable);
This is more logical, and organised. Passing the variable as an argument to the function is way better than using the global keyword within each function.
Alternatively, POST, REQUEST, SESSION and COOKIE variables are all superglobals. This means they can be used within functions without having to implicitly import them:
// Assume the value of $_POST['someText'] is someValue
function getText(){
$someText = $_POST['someText'];
return $someText;
}
echo getText(); // Outputs someValue

function getTierOne()
{
global $opid;
//...
}

Related

Global variable in sub-function no need to declare

whether to do a declare variable when a variable is in a sub-function ?
Like the example carried this:
function cobasaja(){
global $coba;
return $coba;
}
function ditampilkan(){
global $coba;
$coba = "content trying...";
return cobasaja();
}
echo "View: ".ditampilkan();
Why it can not be like this:
function cobasaja(){
global $coba;
return $coba;
}
function ditampilkan(){
//global $coba; <= not declare in viewer function
$coba = "content trying...";
return cobasaja();
}
echo "View: ".ditampilkan();
But the second experiment did not work.
Because as I recall, usually the second way can be done, but now I do it can not, is this because of its PHP version or setting in PHP.ini ?
Adding a function creates a new scope. Any variables you want to use in the function need to be either defined in that scope, brought in from the outer scope with global, or passed in as parameters. This general concept has not changed much over PHP versions as far as I know, so I don't believe your second experiment would have worked in an earlier PHP version, or could work by changing a configuration setting.
If your functions are in the same class, you can use object properties rather than global variables to achieve something like what you want.
class Example {
private $coba = '';
protected function cobasaja() {
return $this->coba;
}
public function ditampilkan() {
$this->coba = "content trying...";
return $this->cobasaja();
}
}

Dynamic php function

How can we declare the function name dynamically?
For example :
$function = 'test'
public $function(){
}
You could use a callback for this:
https://stackoverflow.com/a/2523807/3887342
function doIt($callback) { $callback(); }
doIt(function() {
// this will be done
});
Declaring a function with a variable but arbitrary name like this is not possible without getting your hands dirty with eval() or include().
I think based on what you're trying to do, you'll want to store an anonymous function in that variable instead (use create_function() if you're not on PHP 5.3+):
$variableA = function() {
// Do stuff
};
You can still call it as you would any variable function, like so:
$variableA();

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'];
}

PHP: Global variable scope

I have a separate file where I include variables with thier set value.
How can I make these variables global?
Ex. I have the value $myval in the values.php file. In the index.php I call a function which needs the $myval value.
If I add the include(values.php); in the beggining of the index.php file it looses scope inside the function. I will call the same variable in multiple functions in the index.php file.
Inside the function, use the global keyword or access the variable from the $GLOBALS[] array:
function myfunc() {
global $myvar;
}
Or, for better readability: use $GLOBALS[]. This makes it clear that you are accessing something at the global scope.
function myfunc() {
echo $GLOBALS['myvar'];
}
Finally though,
Whenever possible, avoid using the global variable to begin with and pass it instead as a parameter to the function:
function myfunc($myvar) {
echo $myvar . " (in a function)";
}
$myvar = "I'm global!";
myfunc($myvar);
// I'm global! (in a function)
Use inside your function :
global $myval;
PHP - Variable scope
Using the global keyword in the beginning of your function will bring those variables into scope. So for example
$outside_variable = "foo";
function my_function() {
global $outside_variable;
echo $outside_variable;
}
Is there a reason why you can't pass the variable into your function?
myFunction($myVariable)
{
//DO SOMETHING
}
It's a far better idea to pass variables rather than use globals.
Same as if you declared the variable in the same file.
function doSomething($arg1, $arg2) {
global $var1, $var2;
// do stuff here
}

Declaring a global variable inside a function

I have two PHP files. In the first I set a cookie based on a $_GET value, and then call a function which then sends this value on to the other file. This is some code which I'm using in join.php:
include('inc/processJoin.php');
setcookie("site_Referral", $_GET['rid'], time()+10000);
$joinProc = new processJoin();
$joinProc->grabReferral($_COOKIE["site_Referral"]);
The other file (processJoin.php) will then send this value (among others) to further files which will process and insert the data into the database.
The problem I'm having is that when the grabReferral() function in processJoin.php is called, the $referralID variable isn't being defined on a global scale - other functions in processJoin.php can't seem to access it to send to other files/processes.
I've tried this in processJoin.php:
grabReferral($rid) {
global $ref_id;
$ref_id = $rid;
}
someOtherFunction() {
sendValue($ref_id);
}
But the someOtherFunction can't seem to access or use the $ref_id value. I've also tried using define() to no avail. What am I doing wrong?
you have to define the global var in the second function as well..
// global scope
$ref_id = 1;
grabReferral($rid){
global $ref_id;
$ref_id = $rid;
}
someOtherFunction(){
global $ref_id;
sendValue($ref_id);
}
felix
personally, I would recommend the $GLOBALS super variable.
function foo(){
$GLOBALS['foobar'] = 'foobar';
}
function bar(){
echo $GLOBALS['foobar'];
}
foo();
bar();
DEMO
This is a simple and working code to initialize global variable from a function :
function doit()
{
$GLOBALS['val'] = 'bar';
}
doit();
echo $val;
Gives the output as :
bar
The following works.
<?php
foo();
bar();
function foo()
{
global $jabberwocky;
$jabberwocky="Jabberwocky<br>";
bar();
}
function bar()
{
global $jabberwocky;
echo $jabberwocky;
}
?>
to produce:
Jabberwocky
Jabberwocky
So it seems that a variable first declared as global inside a function and then initalised inside that function acquires global scope.
The global keyword lets you access a global variable, not create one. Global variables are the ones created in the outermost scope (i.e. not inside a function or class), and are not accessible inside function unless you declare them with global.
Disclaimer: none of this code was tested, but it definitely gets the point across.
Choose a name for the variable you want to be available in the global scope.
Within the function, assign a value to the name index of the $GLOBALS array.
function my_function(){
//...
$GLOBALS['myGlobalVariable'] = 42; //globalize variable
//...
}
Now when you want to access the variable from code running in the global scope, i.e. NOT within a function, you can simply use $ name to access it, without referencing the $GLOBALS array.
<?php
//<global scope>
echo $myGlobalVariable; //outputs "42"
//</global scope>
?>
To access your global variable from a non-global scope such as a function or an object, you have two options:
Access it through the appropriate index of the $GLOBALS array. Ex: $GLOBALS['myGlobalVariable'] This takes a long time to type, especially if you need to use the global variable multiple times in your non-global scope.
A more concise way is to import your global variable into the local scope by using the 'global' statement. After using this statement, you can reference the global variable as though it were a local variable. Changes you make to the variable will be reflected globally.
//<non global scopes>
function a(){
//...
global $myGlobalVariable;
echo $myGlobalVariable; // outputs "42"
//...
}
function b(){
//...
echo $GLOBALS['myGlobalVariable']; // outputs "42"
echo $myGlobalVariable; // outputs "" (nothing)
// ^also generates warning - variable not defined
//...
}
//</non global scopes>
Please use global variables in any language with caution, especially in PHP.
See the following resources for discussion of global variables:
http://chateau-logic.com/content/dangers-global-variables-revisited-because-php
http://c2.com/cgi/wiki?GlobalVariablesAreBad
The visibility of a variable
I hope that helped
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>

Categories