Reputation: 7065
I've got a function called myFoo
that performs some operations on the string that is passed to it (in this case, and for simplicity, it just prints it out).
I'd like this function to operate in this way:
When called with a variable, as in myFoo($myBar);
, I would like it to sanitize the variable, before printing it out.
When called with a string, as in myFoo("My name is Bar");
, I want it to skip the string sanitization bit.
The function myFoo
is shown below:
public function myFoo($bar) {
// Determine if $bar was a string, or a variable
if([$bar was passed as a variable]) {
// Sanitize it
$bar = filter_var($bar,FILTER_SANITIZE_STRING);
}
// Otherwise, just print it out without sanitization
// Print it
echo $bar;
}
What should I write in the if
statement in order to determine if the parameter was a direct string or a string variable? Is this even possible? Thanks!
I probably should've clarified my intentions earlier on .. here goes: So I actually meant to use this in order to translate all of the text on my PHP website (across all of the pages). So, instead of writing something like this:
<html>
<head><title>Welcome to the ACME Co. Homepage</title></head>
<body><h1>Welcome to the ACME Co. Homepage</h1>
...
.. I would instead write this:
<html>
<head><title><?= _("Welcome to the ACME Co. Homepage"); ?></title></head>
<body><h1><?= _("Welcome to the ACME Co. Homepage"); ?></h1>
...
The _
method would determine the language setting, and output the string in the correct language. I guess I just wanted to skip the overhead from sanitizing every single thing on the page, as opposed to just sanitizing user input (especially since this function is called very frequently)
Upvotes: 2
Views: 131
Reputation: 780787
You can't tell the difference. When calling a function with a variable argument, the function receives the value of the variable as the parameter. So in both cases, the function just sees a string.
You could add a second argument that says whether the value should be sanitized:
public function myFoo($bar, $sanitize = true) {
if ($sanitize) {
$bar = filter_var($bar, FILTER_SANITIZE_STRING);
}
echo $bar;
}
Then you can call it:
myFoo("My name is Bar", false);
Upvotes: 2