FloatingRock
FloatingRock

Reputation: 7065

How do I know if the parameter passed to a function is a variable or a string?

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:

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!

Update - Further explanation

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

Answers (1)

Barmar
Barmar

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

Related Questions