1

I am having a problem with this code:

$myvariable = "<?php $user_id = '5'; ?>";

...now I then write it to file using php...

and this is what I see when I open the saved file:

<?php  = '5'; ?>

$user_id is missing!

Why is this happening and is there a way to fix this problem?

1
  • PHP will parse the variables in " quoted strings, which will happen before you save string to file action. Commented Oct 30, 2011 at 23:21

2 Answers 2

5

When you use double-quotes, any $variables in the text will be replaced with their current value. Because $user_id isn't defined in the code that's currently running, it's replaced with nothing.

There are a couple of ways to prevent this from happening. You could wrap your string in single-quotes instead, escaping the existing single-quotes in the text with a backslash:

$myvariable = '<?php $user_id = \'5\'; ?>';

Or you cou could instead escape the $ with a backslash, so that it's not interpreted:

$myvariable = "<?php \$user_id = '5'; ?>";
Sign up to request clarification or add additional context in comments.

1 Comment

They could also escape the \$user_id using ", right? (See: codepad.org/xrZUBeXU)
2

PHP interprets variables within strings if you surround the string with double-quotes, as you are using. If you use single-quotes, however, it interprets the string literally.

Try escaping the dollar sign in the variable name. Like this:

$myvariable = "<?php \$user_id = '5'; ?>";

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.