change and initialise variables in a function - php

I was wondering if it's possible to change and initialize variables in a function without passing arguments to the function. Here is what I want to achieve:
$foo = 'Lorem';
$array = array();
foobar($foo);
function foobar(){
if (strlen($foo)== 1)
$bar = 'Ipsum';
else
$array[] = 'error';
}
fubar();
function fubar(){
if (empty($fouten))
echo $bar;
}

$foo is a local (uninitialized) variable inside a function. It is different from the global variable $foo ($GLOBALS['foo']).
You have two ways:
$foo;
$bar;
$array = array();
function foobar(){
global $foo, $array, $bar;
if (strlen($foo)== 1)
$bar = 'Ipsum';
else
$array[] = 'error';
}
or by using the $GLOBAL array …
This is not really good practice though and will become a maintenance nightmare with all those side effects

Functions in php can be given arguments that have default values. The code you posted as written will give you notices for undefined variables. Instead, you could write:
function foobar($foo = null) {
if($foo) { // a value was passed in for $foo
}
else { // foo is null, no value provided
}
}
Using this function, neither of the below lines will produce a notice
foobar();
foobar('test');

Related

Initialize the function In the form of Variable in php

How can i set the function as a variable in php
Similar to list function
example: list($x,$y)=array(1,2); // this is okey ,but...
How do I create such a structure?
You are talking about variable function that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
Here is the little example from PHP manual Variable Functions
function foo() {
echo "In foo()<br />\n";
}
function bar($arg = '')
{
echo "In bar(); argument was '$arg'.<br />\n";
}
// This is a wrapper function around echo
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
and the other scenario is Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
<?php
$my_array = array("Dog","Cat","Horse");
list($a, $b, $c) = $my_array;
echo "I have several animals, a $a, a $b and a $c.";
?>
The list() function is used to assign values to a list of variables. Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.

Why does this not make a difference between property and variable?

class someclass
{
public $foo = 'abcd';
public function __construct($data)
{
$this->foo = $data;
}
public function doSomething()
{
$user = $_POST['username'];
echo $foo = $_POST['foo']; // This output correct value
var_dump($foo); // This Output NULL
$somethingelse = $_POST['foo'];
var_dump($somethingelse); // Output as expected
}
}
If i change my variable name or property name from $foo to something else in do in doSomething() it runs fine.
Why do I need to keep the property name and variable name different here?
Why does $foo is NULL when one of the property name is $foo?
You need to use $this->foo to get and set the classes property
change this
echo $foo = $_POST['foo'];
to
echo $this->foo = $_POST['foo'];
var_dump($this->foo);
When accessing class variables you need to use the $this-> prefix.
Change your code to
echo $this->foo = $_POST['foo'];
var_dump($this->foo);
It is correct and it works fine. I ran your code and it always gives me the same. There's no problem you have property $foo and $foo variable in one or multiple functions. It always give me the same answer.
If $_POST['foo']=test then echo $foo = $_POST['foo']; returns "test", $foo returns "test" and $somethingelse returns "test";

PHP use() function for scope?

I have seen code like this:
function($cfg) use ($connections) {}
but php.net doesn't seem to mention that function. I'm guessing it's related to scope, but how?
use is not a function, it's part of the Closure syntax. It simply makes the specified variables of the outer scope available inside the closure.
$foo = 42;
$bar = function () {
// can't access $foo in here
echo $foo; // undefined variable
};
$baz = function () use ($foo) {
// $foo is made available in here by use()
echo $foo; // 42
}
For example:
$array = array('foo', 'bar', 'baz');
$prefix = uniqid();
$array = array_map(function ($elem) use ($prefix) {
return $prefix . $elem;
}, $array);
// $array = array('4b3403665fea6foo', '4b3403665fea6bar', '4b3403665fea6baz');
It is telling the anonymous function to make $connections (a parent variable) available in its scope.
Without it, $connections wouldn't be defined inside the function.
Documentation.

PHP functions 101 question, really simple

I'm kind of slow in the head so can someone tell me why this isn't working:
function foo() {
$bar = 'hello world';
return $bar;
}
foo();
echo $bar;
I just want to return a value from a function and do something with it.
Because $bar does not exist outside of that function. Its scope is gone (function returned), so it is deallocated from memory.
You want echo foo();. This is because $bar is returned.
In your example, the $bar at the bottom lives in the same scope as foo(). $bar's value will be NULL (unless you have defined it above somewhere).
Your foo() function is returning, but you're not doing anything with it. Try this:
function foo() {
$bar = 'hello world';
return $bar;
}
echo foo();
// OR....
$bar = foo();
echo $bar;
You aren't storing the value returned by the foo function
Store the return value of the function in a variable
So
foo() should be replaced by
var $t = foo();
echo $t;
As the others have said, you must set a variable equal to foo() to do stuff with what foo() has returned.
i.e. $bar = foo();
You can do it the way you have it up there by having the variable passed by reference, like so:
function squareFoo(&$num) //The & before the variable name means it will be passed by reference, and is only done in the function declaration, rather than in the call.
{
$num *= $num;
}
$bar = 2;
echo $bar; //2
squareFoo($bar);
echo $bar; //4
squareFoo($bar);
echo $bar; //16
Passing by reference causes the function to use the original variable rather than creating a copy of it, and anything you do to the variable in the function will be done to the original variable.
Or, with your original example:
function foo(&$bar)
{
$bar = 'hello world';
}
$bar = 2;
echo $bar; //2
foo($bar);
echo $bar; //hello world

What's the purpose of using & before a function's argument?

I saw some function declarations like this:
function boo(&$var){
...
}
what does the & character do?
It's a pass by reference. The variable inside the function "points" to the same data as the variable from the calling context.
function foo(&$bar)
{
$bar = 1;
}
$x = 0;
foo($x);
echo $x; // 1
Basically if you change $var inside the function, it gets changed outside. For example:
$var = 2;
function f1(&$param) {
$param = 5;
}
echo $var; //outputs 2
f1($var);
echo $var; //outputs 5
It accepts a reference to a variable as the parameter.
This means that any changes that the function makes to the parameter (eg, $var = "Hi!") will affect the variable passed by the calling function.
It is pass by reference.
If you are familiar with C pointers, it is like passing a pointer to the variable.
Except there is no need to dereference it (like C).
you are passing $var as reference, meaning the actual value of $var gets updated when it is modified inside boo function
example:
function boo(&$var) {
$var = 10;
}
$var = 20;
echo $var; //gets 20
boo($var);
echo $var //gets 10
The ampersand ( & ) before a variable ( & $foo ) overrides pass by value to specify that you want to pass the variable by reference instead.
For example if you have this:
function doStuff($variable) {
$variable++;
}
$foo = 1;
doStuff($foo);
echo $foo;
// output is '1' because you passed the value, but it doesn't alter the original variable
doStuff( &$foo ); // this is deprecated and will throw notices in PHP 5.3+
echo $foo;
// output is '2' because you passed the reference and php will alter the original variable.
It works both ways.
function doStuff( &$variable) {
$variable++;
}
$foo = 1;
doStuff($foo);
echo $foo;
// output is '2' because the declaration of the function requires a reference.
If any function starts with ampersand(&), It means its call by Reference function. It will return a reference to a variable instead of the value.
function reference_function( &$total ){
$extra = $total + 10;
}
$total = 200;
reference_function($total) ;
echo $total; //OutPut 210

Categories