returning variable from function - php

This is probably not the wisest question, but is it possible to return a variable from a function without redeclaring it?
function test(){
$a = 1;
return $a;
}
Would it somehow be possible to access $a with just calling the function? test();
not $a = test();
Is that the only way? I want to make $a available after calling the function.

You have to put the variable into the global scope:
http://codepad.org/PzKxWGbU
function test()
{
$GLOBALS['a'] = 'Hello World!';
}
test();
echo $a;
But it would be better to use a return value or references:
function test(&$ref)
{
$ref = 'Hello World!';
}
$var = '';
test($var);

I assume you want to change some context when you call the function.
This is possible. For example, all global variables share the same context across your application. If a function set's a global variable, its available in the global scope:
function change_global_variable($name, $value)
{
$GLOBALS[$name] = $value;
}
change_global_variable('a', 1);
echo $a;
However, whenever you do something like this, take care that you're destroying the modularity of your code. For example, if you have 50 functions like this and 80 variables, and then you need to change something, you need to change many, many places. And even harder, you don't remember which places you need to change and how they belong to each other.
It's normally better to make the context an object and pass it to the function that changes it, so it's more clear what the function does:
class Context extends ArrayObject {}
$context = new Context;
function change_context(Context $context, $name, $value)
{
$context[$name] = $value;
}
change_context($context, 'b', 2);
echo $context['b'], "\n";
This example demonstrates something that's called dependency injection. Instead of modifying the only one (global) context that exists in PHP, you are telling the function what it should modify, instead that it modifies hard-encoded global variables
There is a mix form of it, using the global variable scope to contain the context, so you spare to pass it as an additional parameter, however I only show it here for completeness, because it's not helping to retain modularity that well (however it's better than using more than one global variable):
class Context extends ArrayObject {}
$context = new Context;
function change_global_context($name, $value)
{
global $context;
$context[$name] = $value;
}
change_global_context('c', 3);
echo $context['c'], "\n";
Rule of thumb: Avoid global variables. Consider them of being very expensive and you don't want your code to be expensive.

No, it is not due to the scoping.
An option would be to declare $a before and then making it a global. It will then be available inside test:
$a = '';
function test(){
global $a;
$a = 1;
return $a;
}
echo $a; // 1
But may I ask why you want to do this? Are you just playing around or do you have a use case? You're most probably doing it wrong if you need this.

Maybe if you just want to show the variable you can use
function test(){
$a = 1;
echo $a;
return $a;
}
in this way if you want you can save the variable $a in a variable if not you can just show it calling the test function.
Hope it helps.
Nicola.

Related

Global scope not printing data

Why is $a not printing?
And what is the alternate of this, and I dont want to use return.
function abc () {
$a = 'abc';
global $a;
}
abc();
echo $a;
The reason why it's not echoing is because of two things:
1) You need to declare global "before" the variable you wish to define as being global.
and
2) You also need to call the function.
Rewrite:
<?php
function abc()
{
global $a;
$a = 'abc';
}
abc();
echo $a;
For more information on variable scopes, visit the PHP.net website:
http://www.php.net/manual/en/language.variables.scope.php
You can get your variable as:
echo $GLOBALS['a'];
see http://php.net/manual/en/language.variables.scope.php
You can use define():
function abc() {
define("A", "abc");
}
abc();
echo A;
Make sure you call the function. I added that just above echo.
First you must create and assign a variable. And then in you function describe that is a global var you want to use.
$a = 'zxc';
function abc() {
global $a;
$a = 'abc';
}
abc();
echo $a;
This is not really good idea to use golbal such way. I don't really understand why I so much want to use a global var...
But my opinion is better for you to use a pointer to variable.
function abc(&$var){
$var = 'abc';
}
$a = 'zxc';
abc(&$a);
echo $a;
Or even would be better to create an object and then access variable with-in this object

how do I condense this statement?

I have the following function:
<?php
class Test{
function myFunction(){
return array('first','second','third');
}
}
?>
And I can print out the elements of the array:
$var=new Test();
$varr=$var->myFunction();
print($varr[1]);
Is there a way to condense this statement so I don't have to assign $var->myFunction() to a second variable (in this case $varr)?
PHP does not support this very well (as of PHP 5.3) as Tim Cooper already highlighted. So you need to think twice if you really need to have this compacted.
You can do things quite dynamically e.g. by return an ArrayObject instead of an array:
class Test
{
function myFunction()
{
return new ArrayObject(array('first','second','third'), 3);
}
}
$var = new Test();
print($var->myFunction()->{1});
Which will decorate the array data with some additional methods and ways of accessing. Another way would be for functions w/o parameter to fool the PHP parser and offer a property instead of a function dynamically:
class Test
{
function myFunction()
{
return array('first','second','third');
}
public function __get($name)
{
return $this->$name();
}
}
$var = new Test();
print($var->myFunction[1]);
But I don't know if this is really useful in an application.
So check your motivation why you want to compact the code and then decide on your own.
In PHP 5.4 you'll be able to do:
$varr=$var->myFunction()[1];
Until then, using list might help out:
list(,$varr) = $var->myFunction();
Another solution is to modify your method to accept an optional index of the item to return:
function myFunction($index = null){
$arr = array('first','second','third');
return $index == null ? $arr : $arr[$index];
}
$varr = $var->myFunction(1);

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;
?>

Is it possible to access outer local variable in PHP?

Is it possible to access outer local varialbe in a PHP sub-function?
In below code, I want to access variable $l in inner function bar. Declaring $l as global $l in bar doesn't work.
function foo()
{
$l = "xyz";
function bar()
{
echo $l;
}
bar();
}
foo();
You could probably use a Closure, to do just that...
Edit : took some time to remember the syntax, but here's what it would look like :
function foo()
{
$l = "xyz";
$bar = function () use ($l)
{
var_dump($l);
};
$bar();
}
foo();
And, running the script, you'd get :
$ php temp.php
string(3) "xyz"
A couple of note :
You must put a ; after the function's declaration !
You could use the variable by reference, with a & before it's name : use (& $l)
For more informations, as a reference, you can take a look at this page in the manual : Anonymous functions
You must use the use keyword.
$bar = function() use(&$l) {
};
$bar();
In the very very old PHP 5.2 and earlier this didn't work. The syntax you've got isn't a closure, but a definition of a global function.
function foo() { function bar() { } }
works the same as:
function foo() { include "file_with_function_bar.php"; }
If you execute function foo twice, PHP will complain that you've tried to re-define a (global) function bar.
You can read default value by:
function(){
return preg_match(
"yourVar = \d+"
, str_file_get_contents(functionFile)
, arrayToPutFieldsValue
);
}
If You would use two functons in the same time - it's like someone's using a spoon and You want to take a food from that spoon - You'll waste a food or some of You will starv.
Anyway - You would have to set a pointer somehow in a hard way.
It's impossible to get any field from other function or class without calling it to life.
Functions/methods are instance-like - they need to be called.
Share the common fields by accessing a global fields with synchronized functions.
function a()
{
function val1($arg=null)
{
static $a;
if ($arg !== null) $a = $arg;
else return $a;
}
function b()
{
val1('1234');
echo val1() . '<br>'; // shows: 1234
val1('my custom data');
echo val1() . '<br>'; // shows: my custom data
}
b();
}
a();
Used val1('my custom data') to set my value
Used val1() to get my value

PHP access external $var from within a class function

In PHP, how do you use an external $var for use within a function in a class? For example, say $some_external_var sets to true and you have something like
class myclass {
bla ....
bla ....
function myfunction() {
if (isset($some_external_var)) do something ...
}
}
$some_external_var =true;
$obj = new myclass();
$obj->myfunction();
Thanks
You'll need to use the global keyword inside your function, to make your external variable visible to that function.
For instance :
$my_var_2 = 'glop';
function test_2()
{
global $my_var_2;
var_dump($my_var_2); // string 'glop' (length=4)
}
test_2();
You could also use the $GLOBALS array, which is always visible, even inside functions.
But it is generally not considered a good practice to use global variables: your classes should not depend on some kind of external stuff that might or might not be there !
A better way would be to pass the variables you need as parameters, either to the methods themselves, or to the constructor of the class...
Global $some_external_var;
function myfunction() {
Global $some_external_var;
if (!empty($some_external_var)) do something ...
}
}
But because Global automatically sets it, check if it isn't empty.
that's bad software design. In order for a class to function, it needs to be provided with data. So, pass that external var into your class, otherwise you're creating unnecessary dependencies.
Why don't you just pass this variable during __construct() and make what the object does during construction conditional on the truth value of that variable?
Use Setters and Getters or maybe a centralized config like:
function config()
{
static $data;
if(!isset($data))
{
$data = new stdClass();
}
return $data;
}
class myClass
{
public function myFunction()
{
echo "config()->myConfigVar: " . config()->myConfigVar;
}
}
and the use it:
config()->myConfigVar = "Hello world";
$myClass = new myClass();
$myClass->myFunction();
http://www.evanbot.com/article/universally-accessible-data-php/24

Categories