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

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

Related

Is there any way to access variable in other files inside PHP function?

I'm trying to access to variables in other files within a php function. outside of the function it brings the value that i want without problems but i don't know why if i try to access to the variable inside the php function, i can't access the value.
i have a file called name.php
<?php
$name1 = "aa";
$name2 = "bb";
?>
and in index.php i'm trying to access to the variables in name.php like this.
<?php
include_once('name.php');
echo $name1;
name();
function name(){
echo $name1;
}
?>
as i said i can print the name1 variable outside the function but not inside.
can i know why and how to access to the variables in this case?
Thank you
Your problem comes from a basic of PHP : the scope of functions is local, not global, contrary to JavaScript.
You could use globals to achieve what you want to do, but I strongly discourage you to use them.
To me, your best shot is to pass your variables directly to your function, or to use closures.
// Example 1 : pass variables to the function
function name($name1) {
echo $name1;
}
// Example 2 : use a closure
$myNameFunc = function() use($name1) {
echo $name1;
};
You can read more about closures from the PHP documentation.
In PHP (and many other languages) the variables are visible only in the scope in which they are defined. In your example:
<?php
$name1 = "aa";
$name2 = "bb";
//this is the *global* scope
?>
<?php
include_once('name.php');
echo $name1; // you are still in the global scope so $name1 is defined
name();
function name(){
echo $name1; // here you are in the name() function scope. The variable $name is not defined here
}
?>
There are 2 ways to access variables from the global scope inside a function. One them is using the keyword global when defining your variable. That makes the variable visible inside all scopes which are inside the "global" scope. That is not recommended since the variable will be visible in scopes in which you don't need it (and other reasons maybe someone could explain better).
The best thing you can do is to pass your variable as a parameter to your function.
You can define the function like this:
function name($param){
echo $param;
}
And later call your function like this:
name($name1);
You can use Global variable or you can add parameter to your function to pass the value.
By using Global:
echo name();
function name(){
global $name1, $name2;
echo $name1;
}
By Adding function parameter:
echo name($name1);
function name($name1){
echo $name1;
}
You are not passing values to the function. Try this
function name($name1){
echo $name1;
}
Use global $name; inside function
Read more about globals Variable.

PHP using variable in an included function

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;
//...
}

PHP variable defined outside callback function is unaccessible inside the function

I'm trying to use $variable inside my callback function. I pass it to another function like this: functionName("egTraders_ItemDataBound"), inside that function I assign it to a variable and the call it like this: $theAssignedFunctionVariable($this, $rowToAdd);
And the function egTraders_ItemDataBound gets called properly but the variable $variable
is undefined. What can I do?
<?php
$variable = "var";
function egTraders_ItemDataBound($sender, $param1) {
echo $variable;
}
?>
If You are running PHP 5.3+ You can achive this by simply creating anonymous functioin with use keyword ( documentation ) :
$bar = 'bar';
$f = function() use ($bar)
{
var_dump($bar);
};
function bar( $fName )
{
$fName();
}
bar($f);
You could pass it in as a param or you could use it as a global in the function. I do not recommend the latter. You should stay away from globals.
Edit for example
$variable = "var";
function egTraders_ItemDataBound($sender, $param1) {
global $variable;
echo $variable;
}
egTraders_ItemDataBound(NULL, NULL);
you need to declare the variable as global because it is out of scope
$variable = "var";
function egTraders_ItemDataBound($sender, $param1) {
global $variable;
echo $variable;
}
The variable is declared outside of the scope of the function. You should revisit your design. I strongly recommend against using global variables as that is poor practice.

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
}

alias to include

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".

Categories