0

I am trying to build an "escape" function (as an exercise). The objective of this function is to transform "dangerous" values into safe values to be inserted in a database. The content of this function is not important.

function escape(&$value){

    //some code

    return $value;
}

Here's the problem: I want to make this function very handy to use, therefore it should be able to support 2 possible scenarios:

1) returning a safe value:

$safe_val = escape($unsafe_val);

2) changing a variable "by reference":

escape($value);

At the moment, my function does its job, however...if I pass something like:

$safe_val = escape(php_native_change_string_to_something($value));

PHP gets angry and says:

Notice: Only variables should be passed by reference

How can I make PHP accept that if something can't be passed by reference it does not matter and it should just ignore the error and continue the execution?

5
  • just create another variable to store the previous result. What's the point here ? Commented Dec 24, 2020 at 15:54
  • The point is to make the code shorter Commented Dec 24, 2020 at 16:03
  • Sometimes shorter means less readable. Anyways, this is a language feature and you must respect it. To conclude your code won't work. Commented Dec 24, 2020 at 16:05
  • You can simply use prepared statements. Commented Dec 24, 2020 at 16:27
  • Passing by reference seems easier to use but it's a source of unexpected behaviour and hidden bugs. Commented Dec 24, 2020 at 18:48

1 Answer 1

1

PHP is complaining because the value being passed into escape by escape(php_native_change_string_to_something($value)) is a temporary value (rvalue). The argument has no permanent memory address so it does not make sense to modify the value.

However, despite this not making sense, PHP will still do what you want. You are receiving a notice, not an error. Your code should still produce the output you are expecting. This short program models your setup:

<?php

function escape (&$s) {
    return $s;
}

$s = 'TEXT TO ESCAPE';

$new_s = escape( strtolower( $s ) );

echo "$s\n";
echo "$new_s\n";

and produces the following results:

s: TEXT TO ESCAPE
new_s: text to escape

If you would like to get rid of the notice you will need to use the error control operator (@), @escape(php_native_change_string_to_something($value)).

Despite this being something that will work in PHP I would suggest avoiding this type of usage as it will decrease code readability and is not suggested by PHP (as the notice indicates).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.