0

I want to mix a variable after call a function, but not when I set the variable.

My example code:

<?php $greeting = "hi! {$gbye}"; function greetings() { global $greeting; $gbye = "goodbye!"; return $greeting; } echo greetings(); ?> 

Fiddle: http://phpfiddle.org/main/code/kd5w-p7q4

I tried escaping the $ symbol: \$, but this only gives me the complete text. And replacing the escaped symbol make the same.

The $gbye variable is inside a language file, by this reason, I have to save the word ($gbye) until I call the function (to replace it as if the full string ($greeting = "hi! {$gbye}";) was inside the function). It's just an example.

So what can I do?

6
  • 2
    not going to tell you how, as its almost always bad practice to use variable variables Commented Dec 7, 2015 at 23:56
  • @dagon. I agree. There is way to do it. But there is also more simple way to achieve the same result. Commented Dec 8, 2015 at 0:01
  • I made an edit specifying what I want to achieve ;) Commented Dec 8, 2015 at 0:07
  • $greeting = "hi! ".$gbye; will work just fine as long as the variable is in scope Commented Dec 8, 2015 at 0:11
  • 1
    "as long as the variable is in scope" seems your only problem is understanding variable scope Commented Dec 8, 2015 at 0:18

1 Answer 1

0

For language file usage, you may want to use your own meta keyword, instead of php variable syntax. This is ensure what you want to do is seperated from what PHP wants to do. This will save you from future bugs and maintenance effort. For example,

<?php $greeting = "hi! #gbye#"; function greetings() { global $greeting; return str_replace("#gbye#", "goodbye!", $greeting); } echo greetings(); ?> 
Sign up to request clarification or add additional context in comments.

1 Comment

Because it's not as easy as that... The $gbye variable is inside a language file, by this reason, I have to save the word ($gbye) until I call the function (to replace it as if the full string ($greeting = "hi! {$gbye}";) was inside the function). It's just an example. ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.