I'm 'dissecting' PunBB, and one of its functions checks the structure of BBCode tags and fix simple mistakes where possible:
function preparse_tags($text, &$errors, $is_signature = false)
What does the & in front of the $error variable mean?
It means pass the variable by reference, rather than passing the value of the variable. This means any changes to that parameter in the preparse_tags function remain when the program flow returns to the calling code.
function passByReference(&$test) {
$test = "Changed!";
}
function passByValue($test) {
$test = "a change here will not affect the original variable";
}
$test = 'Unchanged';
echo $test . PHP_EOL;
passByValue($test);
echo $test . PHP_EOL;
passByReference($test);
echo $test . PHP_EOL;
Output:
Unchanged
Unchanged
Changed!
It does pass by reference rather than pass by value.
This allows for the function to change variables outside of its own scope, in the scope of the calling function.
For instance:
function addOne( &$val ) {
$val++;
}
$a = 1;
addOne($a);
echo $a; // Will echo '2'.
In the case of the preparse_tags function, it allows the function to return the parsed tags, but allow the calling parent to get any errors without having to check the format/type of the returned value.
It accepts a reference to a variable as the parameter.
This means that any changes that the function makes to the parameter (eg, $errors = "Error!") will affect the variable passed by the calling function.
It means that the variable passed in the errors position will be modified by the called function. See this for a detailed look.
Related
I created a function to check for special characters in a string, but I can't seem to get it to echo the response message
Here is my code
<?php
function chk_string($string){
if (preg_match('/[\^£$%&*()}{##~?><>|=_+¬-]/', $string))
{
$chk_str="false";
} else {
$chk_str="true";
}
return $chk_str;
}
$string="this is just a test" ;
chk_string($string) ;
echo $chk_str;
?>
The "echo $chk_str" is not echoing anything.
If you did
$chk_str = chk_string($string);
then you could echo $chk_str;.
The $chk_str you are trying to echo is only visible in your function.
More description:
Your function (chk_string) is in a different scope than your echo.
Your function returns a variable, but that variable is "lost", since you don't assign it to another variable.
Your code currently does something like this line by line:
Your function declaration
$string means "this is just a test"
your functions result as a string, just floating in the code
write out a variable that doesn't exist.
I hope this helped in someway.
You need to store returned value in a particular variable if you want to echo that variable like this,
$chk_str = chk_string($string) ;
echo $chk_str;
Another way you can just directly echo returned value like this,
echo chk_string($string) ;
Your question is about variable scope and it is answered already, but I would recommend you to take a look at variable scope here https://www.php.net/manual/en/language.variables.scope.php.
Basically, every variable has its scope and we can not access a variable outside its scope. In your case, scope of variable $chk_str is inside function chk_string so you can not access it outside of the function. Because you return value of $chk_str in function chk_string so you still can access its value through response of function chk_string, for example:
echo chk_string('a string');
OR
$result = chk_string('a string');
echo $result;
I need to make a function that reads my variables at the top and fixes the string so that each word in it has a capital letter. The way I'm currently doing it doesn't seem to work. Here is what I have:
<?php
$course1 = "advanced web development";
$course2 = "mobile app development";
$course3 = "info systems with business intell";
function fixCourseName($courseName) {
$courseName = ucwords($courseName);
}
fixCourseName($course1);
echo $course1;
?>
Does anyone know what would be causing the output to still be lower case?
You can either pass it by reference, by using the & operator in front of the variable when passing it as an argument. This will change the variable you pass through, without having to return it. The variable is then changed in the global scope.
function fixCourseName(&$courseName) {
$courseName = ucwords($courseName);
}
fixCourseName($course1);
echo $course1;
PHP docs: Passing by Reference
You can also return the new value, but then it must be assigned again.
function fixCourseName($courseName) {
return ucwords($courseName);
}
$course1 = fixCourseName($course1);
echo $course1;
The better solution, if the fixCourseName() function does nothing more than using ucwords(), you might as well just use
$course1 = ucwords($course1);
echo $course1;
See this live demo to see it all in action.
Your function gets a copy of the string passed to it and then updates it. If you want to it affect the original variable that's passed to it, you need to pass it by reference, by adding a &:
function fixCourseName(&$courseName) {
# Here ------------^
$courseName = ucwords($courseName);
}
If your function is just calling ucwords, you don't really need it - just call ucwords directly:
$course1 = ucwords($course1);
If I try this code :
<?php
class ref
{
public $reff = "original ";
public function &get_reff()
{
return $this->reff;
}
public function get_reff2()
{
return $this->reff;
}
}
$thereffc = new ref;
$aa =& $thereffc->get_reff();
echo $aa;
$aa = " the changed value ";
echo $thereffc->get_reff(); // says "the changed value "
echo $thereffc->reff; // same thing
?>
Then returning by reference works and the value of the object property $reff gets changed as the variable $aa that references it changes too.
However, when I try this on a normal function that is not inside a class, it won't work !!
I tried this code :
<?php
function &foo()
{
$param = " the first <br>";
return $param;
}
$a = & foo();
$a = " the second <br>";
echo foo(); // just says "the first" !!!
it looks like the function foo() wont recognize it returns by reference and stubbornly returns what it wants !!!
Does returning by reference work only in OOP context ??
That is because a function's scope collapses when the function call completes and the function local reference to the variable is unset. Any subsequent calls to the function create a new $param variable.
Even if that where not the case in the function you are reassigning the variable to the first <br> with each invocation of the function.
If you want proof that the return by reference works use the static keyword to give the function variable a persistent state.
See this example
function &test(){
static $param = "Hello\n";
return $param;
}
$a = &test();
echo $a;
$a = "Goodbye\n";
echo test();
Echo's
Hello
Goodbye
Does returning by reference work only in OOP context ??
No. PHP makes no difference if that is a function or a class method, returning by reference always works.
That you ask indicates you might have not have understood fully what references in PHP are, which - as we all know - can happen. I suggest you read the whole topic in the PHP manual and at least two more sources by different authors. It's a complicated topic.
In your example, take care which reference you return here btw. You set $param to that value - always - when you call the function, so the function returns a reference to that newly set variable.
So this is more a question of variable scope you ask here:
Variable scope
I'm writing my own debug functions and I need some help to fix the code below.
I'm trying to print a variable and its name, the file where the variable and the function was declared and the line of the function call. The first part I did, the variable, the variable name, the file and the line is printed correctly.
At the code, a($variable) works good.
The problem is I'd like this function accepts a string too, out of a variable. But PHP returns with a fatal error (PHP Fatal error: Only variables can be passed by reference in ...). At the code, a('text out').
So, how can I fix this code to accept a variable or a string correctly?
code (edited):
function a(&$var){
$backtrace = debug_backtrace();
$call = array_shift($backtrace);
$line = $call['line'];
$file = $call['file'];
echo name($var)."<br>".$var."<br>".$line."<br>".$file;
}
$variable='text in';
a($variable);
a('text out');
I need pass the variable by reference to use this function below (the function get the variable name correctly, works with arrays too):
function name(&$var, $scope=false, $prefix='unique', $suffix='value'){
if($scope) $vals = $scope;
else $vals = $GLOBALS;
$old = $var;
$var = $new = $prefix.rand().$suffix;
$vname = FALSE;
foreach($vals as $key => $val) {
if($val === $new) $vname = $key;
}
$var = $old;
return $vname;
}
The way your code is currently implementing pass by reference is perfect by design, but also by design cannot be changed to have two a() methods - one accepting a variable by reference and the other as a string-literal.
If the desire to pass a string literal instead of assigning it to a variable first is really needed, I would suggest creating a second convenience method named a_str() that actually accepts a string-literal instead of a variable by reference. This method's sole-purpose would be to relay the variable(s) to the original a() method - thereby declaring a variable to pass by reference.
function a_str($var) {
a($var);
}
The only thing to remember is, use a($variable); when passing by reference and a_str('some text'); when not.
Here is the same convenience-method for your name() function:
function name_str($var, $scope=false, $prefix='unique', $suffix='value'){
return name($var, $scope, $prefix, $suffix);
}
The only way to do what you are asking without writing an additional function like #newfurniturey suggests is plain and simply opening and parsing the file where your function was called as text (e.g. with fopen), using the data from debug_backtrace. This will be expensive in terms of performance, but it might be ok if used only for debugging purposes; and using this method you will no longer need a reference in your function, which means you can freely accept a literal as the parameter.
(1) I want to know what is the difference between call by value and call by reference in php. PHP works on call by value or call by reference?
(2) And also i want to know that do you mean by $$ sign in php
For example:-
$a = 'name';
$$a = "Paul";
echo $name;
output is Paul
As above example what do u mean by $$ on PHP.
$$a = b; in PHP means "take the value of $a, and set the variable whose name is that value to equal b".
In other words:
$foo = "bar";
$$foo = "baz";
echo $bar; // outputs 'baz'
But yeah, take a look at the PHP symbol reference.
As for call by value/reference - the primary difference between the two is whether or not you're able to modify the original items that were used to call the function. See:
function increment_value($y) {
$y++;
echo $y;
}
function increment_reference(&$y) {
$y++;
echo $y;
}
$x = 1;
increment_value($x); // prints '2'
echo $x; // prints '1'
increment_reference($x); // prints '2'
echo $x; // prints '2'
Notice how the value of $x isn't changed by increment_value(), but is changed by increment_reference().
As demonstrated here, whether call-by-value or call-by-reference is used depends on the definition of the function being called; the default when declaring your own functions is call-by-value (but you can specify call-by-reference via the & sigil).
Let's define a function:
function f($a) {
$a++;
echo "inside function: " . $a;
}
Now let's try calling it by value(normally we do this):
$x = 1;
f($x);
echo "outside function: " . $x;
//inside function: 2
//outside function: 1
Now let's re-define the function to pass variable by reference:
function f(&$a) {
$a++;
echo "inside function: " . $a;
}
and calling it again.
$x = 1;
f($x);
echo "outside function: " . $x;
//inside function: 2
//outside function: 2
You can pass a variable by reference to a function so the function can modify the variable.
More info here.
Call by value: Passing the variable value directly and it will not affect any global variable.
Call by reference: Passing the address of a variable and it will affect the variable.
It means $($a), so its the same as $name (Since $a = 'name'). More explanation here What does $$ (dollar dollar or double dollar) mean in PHP?
Call by value means passing the value directly to a function. The called function uses the value in a local variable; any changes to it do not affect the source variable.
Call by reference means passing the address of a variable where the actual value is stored. The called function uses the value stored in the passed address; any changes to it do affect the source variable.