Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Function Variables and Concatenation in PHP

Consider the following:

$var = 'foo' . 'bar'; # Not a member of a class, free-standing or in a function.

As soon as I mark $var as static, however:

static $var = 'foo' . 'bar';

PHP (5.3.1 on a WAMP setup) complains with the following error:

Parse error: syntax error, unexpected '.', expecting ',' or ';'

It seems that the string concatenation is the culprit here.


What's going on here? Can someone explain the rules for static variables to me?

like image 203
jklanders Avatar asked Feb 12 '11 06:02

jklanders


People also ask

What are static variables and functions in PHP?

Definition and Usage The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

What is concatenation in PHP?

The PHP concatenation operator (.) is used to combine two string values to create one string.

Does PHP have static variables?

Introduction: A static class in PHP is a type of class which is instantiated only once in a program. It must contain a static member (variable) or a static member function (method) or both. The variables and methods are accessed without the creation of an object, using the scope resolution operator(::).

What is variable concatenation?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect.


2 Answers

The manual states, in Variables scope:

Trying to assign values to these [static] variables which are the result of expressions will cause a parse error.

There is also mention of it in Static keyword:

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed.

Although it should be noted that a property, static or not, cannot be initialized using an expression neither.

like image 131
netcoder Avatar answered Oct 07 '22 04:10

netcoder


You can not do expressions in initializers. You can, however, do this:

define('FOOBAR', 'foo'.'bar');
static $var = FOOBAR;
echo $var;

Little known fact is that even though initializers can not contain runtime expressions, it can contain constants which can be defined and resolved at runtime. The constant has to be defined by the time $var is first used though, otherwise you'll get string identical to the constant (e.g. "FOOBAR").

like image 35
StasM Avatar answered Oct 07 '22 04:10

StasM