PHP Static Variables in Double Quotes

PHP static variables in double quotes

Sorry, you can't do that. It only works for simple expressions. See here.

Trouble using PHP complex (curly) syntax with static variables

What you want is simply not possible.

Functions, method calls, static class variables, and class constants
inside {$} work since PHP 5. However, the value accessed will be
interpreted as the name of a variable in the scope in which the string
is defined. Using single curly braces ({}) will not work for accessing
the return values of functions or methods or the values of class
constants or static class variables.

The easiest way around would be to just move the var access outside the string.

class asdf{
public static $variable = 'foo@';

public static function getValue() {
return asdf::$variable . 'bar.com';
}
}

doing this, you could even use the variable var syntax, if you need to

class asdf{
public static $variable = 'foo@';

public static function getValue($var = "variable") {
return asdf::$$var . 'bar.com';
}
}

Accessing static variable in quotes from inside static function

By manual:

Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

Read more string ...

Static variable string parsing in PHP

Variable parsing in PHPs double quoted strings only works for "variable expressions". And these must always start with the byte sequence {$. Your reference to a static identifier however starts with {T hencewhy PHP parses towards the next $ in your double quotes and ignores Test::

You need to utilize some cheat codes there. Either use a NOP wrapper function:

$html = "htmlentities";
print "Hello {$html(Test::$var)}";

Or pre-define the class name as variable:

$Test = "Test";
print "Hello {$Test::$var}";

I'm afraid there's no native way to accomplish this otherwise.

PHP single quotes within the double quote

Your usage of quotes is correct, but you're using prepared statements incorrectly - your code is vulnerable to SQL injection! Instead, use placeholders (without quotes) in the query, and pass in the actual values later, as in the example:

$first_name = $_POST['first_name'];
$first_name = trim($first_name);
$last_name = $_POST['last_name'];

$stmt = $con->prepare("insert into reg_data (first_name, last_name)
values(:first_name, :last_name)");
$stmt->execute(array(':first_name' => $first_name, ':last_name' => $last_name));


Related Topics



Leave a reply



Submit