Calling functions with variables that cannot be defined

If I have the following statement:

$b = empty($a) ? "null" : "'$a'" 

To avoid copy and paste, I would like to add it to a function:

 function x($a) { return empty($a) ? "null" : "'$a'" } 

So, I can do:

 $b = x($a); // $a is not defined, so PHP complains $d = x($c); // same with $c 

But then I would get an error from PHP because $a not defined. Is there any way to do this except using the @ operator?

EDIT: I mean the error that occurs when x () is called, and not inside x (). You know, you can do isset () and empty () on everything that is not defined, and PHP will never complain. But if you call the function with something undefined, PHP will complain. What is the problem.

+4
source share
3 answers

First of all, this is not a mistake, but a notification, so you can turn it off.

Secondly, you can define this parameter as passed by reference to avoid notification.

 error_reporting(E_ALL); function x(&$a) { var_dump('inside', $a); return empty($a) ? "null" : "'$a'"; } $a = 4; var_dump('before', isset($a), isset($c)); $b = x($a); $d = x($c); var_dump('after', isset($a), isset($c)); var_dump($b, $d); 

output:

 string(6) "before" bool(true) bool(false) string(6) "inside" int(4) string(6) "inside" NULL string(5) "after" bool(true) bool(false) string(3) "'4'" string(4) "null" 
+3
source

You can also do this:

 $a = 5; $b = "hi"; function var_test($var) { global ${$var}; return isset(${$var}) ? ${$var} : null; } var_dump(var_test("a")); var_dump(var_test("b")); var_dump(var_test("c")); 

Reason ${"var_name"} will be changed to $var_name

+1
source

As written here http://www.php.net/manual/en/functions.arguments.php you can do something like this:

 function x($a=NULL) { return empty($a) ? "null" : "'$a'" } 
-one
source

Source: https://habr.com/ru/post/1491846/


All Articles