2

This is my case.(i changed my case)

I have variable let say $var1 from database and method test($var1)

$var1 = getFromDatabase(); 
//now $var1 contaion "This is new variable".$var2

Then in test method i will do simple string operation from the $var1 equation.

test($var1){
  $var2 = "variable 2";
  //I want to extract $var1 so that string will be combined
  $value = $var1;

  $value_expected = "This is new variable".$var2;
}

But $value will contain "This is new variable".$var2. I expect $value contain This is new variable variable 2 from the $var1 equation.

Is there any solution? Is that possible to do?

Thank You.

2 Answers 2

1

Don't use quotes. $var1 = $var2 + $var3;

Quotes mean you're working with strings

Apart from that, you can't access local variables like that. Variables declared inside the function will not be accessible outside of it. And even if you could you would still not be getting what you expect because you're using $var2 and $var3 before initializing them.

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

1 Comment

thanks for ur response. 1. i wont access $var2 and $var3 from outside. 2. i want to make $var1 dynamic. $var1 contain equation. then method test will compute simple equation from $var1.
0

What you're looking for is possible by passing functions around. For example:

function test( $var1 ) {
    $var2 = 4;
    $var3 = 5;

    // this line calls the function named in $var1 with $var2 and $var3 as arguments
    $value = call_user_func( $var1, $var2, $var3 );

    // in later versions of PHP you can do this instead:
    // $value = $var1( $var2, $var3 );
}

function addThem( $a, $b ) {
    return $a + $b;
}
test( 'addThem' );

Notice that the method of combining variables is passed as a function (or at least, the closest PHP has to passing functions around; PHP is an odd language). Also the values it works on must be passed as parameters.

2 Comments

Thx for ur response. yes it will work in my first case although it will took long time process. Please look my second case. Is that possible to make $value has same output with $value_expected ?
@guurnita your updated question would give you serious security risks. A better solution is to use pre-decided tokens like <<VAR1>> which can be put into the string, then str_replace them in the function (you could even str_replace the $var1 names, but that seems like it would be confusing to users)

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.