guurnita
guurnita

Reputation: 457

PHP variable behavior or convention

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.

Upvotes: 2

Views: 53

Answers (2)

Dave
Dave

Reputation: 46349

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.

Upvotes: 0

php_nub_qq
php_nub_qq

Reputation: 16055

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.

Upvotes: 1

Related Questions