Strict Standards php error - php

I have a small issue with my script.
I'm getting Strict Standards: Only variables should be passed by reference in
if( $checkDNS && ($domain = end(explode('#',$email, 2))) )

From the PHP manual:
This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.
So you must use a variable in the end function:
$domain = explode('#',$email, 2);
if( $checkDNS && ($domain = end($domain)) )

From the manual:
mixed end ( array &$array )
end takes the array by reference and move the internal pointer. Your array is the function output, so its unable to correctly modify the array by reference.

Like the message says, end expects a variable because its parameter is a reference.
But since PHP 5.4 you can dereference arrays like that:
$domain = explode('#',$email, 2)[1];
Assuming that $email always contains #. You should assure that beforehand, otherwise end(...) would give you unexpected results too.

Related

How to dynamically set the argument to $_GET or $_POST?

I'm writing a function in php to check, if all arguments are set. This is for preventing the program to crash when a argument isn't set.
Unfortunately I get this error:
Notice: Undefined variable: _POST
The code running is the following:
# check for the right arguments
function checkArguments($type, $arg_array) {
# $type is either 'GET' or 'POST'
# $arg_array is an array with all the arguments names
foreach($arg_array as $arg) {
print(${"_" . $type}["name"]);
$type = "_" . $type;
if(!isset($$type[$arg])) {
$missing[] = $arg;
}
}
}
HI I will assume you wanted a variable variable, I try to avoid them as they are very hard to read in code. It also breaks ( or doesn't work in ) most IDE editors.
One thing I just saw that is relevant.
http://php.net/manual/en/language.variables.variable.php
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.
The $_POST would be counted among the "Superglobal" as is $_GET
You could assign them to a temporary variable and use that.
$arr = $_GET;
if ($type == "POST") $arr = $_POST;

Are arrays passed by reference or value in PHP?

Are arrays passed by reference or value in PHP?
For example, let's see this code.
function addWeight($arout, $lineCountry, $lineDomain, $target, $weight)
{
$currentDomain=getDomain();
$currentCountry=getCountry();
if ($currentCountry==$lineCountry && ($currentDomain == $lineDomain || $lineDomain==""))
{
$tarobreakpoint=0;
$arout [$target] = intval($weight);
}
return $arout;
}
Basically it took an array as a parameter. Depending on some circumstances it adds elements to the array. I wonder if this is efficient? If $arout is passed by reference like all arrays should then I think it's efficient. But if it's just copied and passed by value then well it's not.
So what's the verdict?
According to the manual, PHP arrays are passed by value:
Array assignment always involves value copying. Use the reference operator to copy an array by reference.
If you'd like to pass an array's reference, use the corresponding operator (&) as mentioned above, and remove the return $arout; line in the addWeight() function:
<?php
// pass $array by reference using & operator
addWeight(&$array, $lineCountry, $lineDomain, $target, $weight);

Parse error: syntax error, unexpected 'unset' (T_UNSET)

I am using simple php unset() function to remove and index of array but it's showing the following error:
Parse error: syntax error, unexpected 'unset' (T_UNSET)
Here is my erroneous code:
echo $totalArray = unset($linkExtHelp[0]);
Thanks in advance.
Try this, Reason for unset($linkExtHelp[0]) assigning to the variable echo $totalArray =
You can't assign the unset() value to the variable, You can use to check before unset and after unset as like below. In other words, unset does not have any return value, since unset is a void. Void - does not provide a result value to its caller.
Syntax: void unset ( mixed $var [, mixed $... ] )
echo "Before unset: ".$linkExtHelp[0];
unset($linkExtHelp[0]);
$linkExtHelp = array_values($linkExtHelp);
echo "After unset: ".$linkExtHelp[0];
instead of
echo $totalArray = unset($linkExtHelp[0]);
unset does not return a value - it cannot be used meaningfully as an expression, even if such a production was accepted.
However, the parse error is caused because unset is a keyword and a "special production": even though unset looks like a function, it is not a function1. As such, unset is only valid as a statement2 per the language grammar.
The production can be found in zend_language_parser.y:
309 unticked_statement:
| ..
338 | T_UNSET '(' unset_variables ')' ';'
1 The syntax is due to historical design choices, and arguably a mistake from a consistency viewpoint:
Note: Because [unset] is a language construct and not a function, it cannot be called using variable functions.
2 There is also "(unset) casting", but I'm ignoring that here.
Unset does not return anything, it is a keyword.
I assume you want to re-index the array, you can use array_values to do this
Try this:
unset($linkExtHelp[0]);
$totalArray = array_values($linkExtHelp);
You can't assign "unset". this is how I do.
you need to make a temp array.
$totalArray = $linkExtHelp; // assign it to a new array (so you can keep the original one )
foreach ($totalArray as $key => $value) {
unset($totalArray [$key]['save_day']); // if you need to remove all of 'save_day' value from multi array
}
var_dump($totalArray); // after unset
var_dump($linkExtHelp); // the original array
//echo $totalArray = unset($linkExtHelp[0]); // This is wrong. no echo
I hope it helps.

PHP braces and conditional

What does this line mean?
if ( ${fun("str1")} (fun("str2"), ${fun("str3")}) )
Evaluate function returning_value_for_str1_of_fun()_name with the parameters return value for str2 and variable with name return_value_for_str3 ?
This tests the return value of the function, whose name is the value in the variable named fun("str1"), and given the arguments fun("str2") and the value of the variable named fun("str3").
Example:
If fun("str1") equals "x", fun("str2") equals 34, and fun("str3") equals "y", then the statement would look like:
if ( $x (34, $y) )
fun("str1") returns string that should be name of variable and the value of this variable is anonymous function (that probably is not void and returns boolean) that gets two arguments first is return value fun("str2") and the second is the value of the variable with the name that matches string returned by fun("str3").
Wow. That's convoluted code. Let's examine it bit by bit:
Let's start with this:
fun("str1")
In fact, this is simply a function call to a function named fun(), passing in a string value as a parameter.
This function call is repeated three times in your code, with different strings as the arguments. The function fun() itself is not supplied in your example code, so I can't tell what it does, but given the context I assume it returns a string.
Which leads us onto the next bit we can examine:
${fun("str1")}
The ${...} syntax in PHP takes the contents of the braces and references a variable of that name.
So, for example, ${"myvar"} is the same as saying $myvar. This is called a dynamic variable name. While it does have its uses, it is a very easy way to write bad code, that is difficult to read, understand or maintain. Your example definitely falls into this category.
However, now that we understand the syntax, it's easy to see that it is taking the string output of the fun() function call, and turning it into a variable name.
Expanding further, we can rewrite the code as follows to make it clearer:
$var1 = fun("str1");
$var2 = fun("str2");
$var3 = fun("str3");
if ( $$var1 ($var2, $$var3) )
Here, $$var1 is being used as a function name, called with $var2 and $$var3 as parameters.
So in $var1, we have a function call returning a string that is being referenced as a variable name, which is being called as a function.
We still don't know what fun() function returns, or whether the variable names that are generated by its return are valid, but we can make some assumptions, as $var1 and $var2 would need to be populated with valid function names in order for your line of code to work at all.
We now have an understanding of the whole line of code, but still not a clear view of what it's trying to acheive (beyond being excessively 'clever' and obtuse).
This is very very poorly written code. It is deliberately obscure, and inefficient (ie it will run slowly).
Some work around:
$func = 'fun';
$str3 = 'str3';
echo ${fun("str1")} (fun("str2"), ${fun("str3")}); // will output 'str2'
function fun($param1, $param2 = ''){
if($param1 == 'str2' || $param1 == 'str3')
return $param1;
elseif($param1 == 'str1')
return 'func';
else
echo ' you are done';
}
Evaluates as follows:
fun("str1") -> 'func'
${fun("str1")} -> $func -> fun
fun("str2") -> 'str2'
fun("str3") -> 'str3'
${fun("str3")} -> $str3
${fun("str1")} (fun("str2"), ${fun("str3")})
=> $func ("str2", $str3)
=> fun("str2", "str3")
=> "str2"

PHP. Pass variable by reference vs string. How to works with these two different arguments?

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.

Categories