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?
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.
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").
I do this:
class MyClass {
static $var1;
static $var2;
public static function _init() {
self::$var1 = 'slkslk' . 'sksks' . 'arbitrary' ;
self::var2 = <<<EOT
<root>
<elem1>skjsksj</elem1>
</root>
EOT;
}
}
MyClass::_init();
Related
After swapping some of my non-static vars to static vars, I ended up with some expressions similar to the one here. This throws a syntax error, but I can't figure out why.
Class Bar {
public static $name = "bar";
}
Class Foo {
public function getParent(){
$this->parentClass = new Bar();
return $this;
}
}
$foo = (new Foo())->getParent();
echo ($foo->parentClass)::$name; //this line is throwing a syntax error
//output:
PHP Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
If I assign the object to a variable, then it doesn't throw the error:
$class = $foo->parentClass;
echo $class::$name;
//outputs "bar";
I could imagine possibly running into some unintended order of operations issues, but can't figure out why it's a syntax error, and I'm wondering if there is a way to do this in a single one line expression. (Since this issue was caused by a mass find/replace, it would be nice to keep it in one line)
It's kinda ugly, but if you really need a one-liner:
echo get_class_vars(get_class($foo->parentClass))["name"];
Inspired by this answer
DEMO
In fact this is only possible as of PHP 7.0. The changed behaviour is not well documentated. I think it's more of a bugfix than a new feature.
However the closest solution to a "one-liner" (working in 5.6) seems to be this one:
$bar = (new Foo())->getParent()->parentClass;
echo $bar::$name;
Maybe that is not what you tried to achieve.
The important thing is that the static class is only accessable by putting it into a single variable first.
I recommend a migration to PHP7 urgently.
Can some one explain why this doesn't work:
private static $bundles = array(
'page-builder' => array(
'Freya\\Bundle\\PageBuilder' => self::$baseDir . '/freya-bundle-pagebuilder/Freya/Bundle/PageBuilder'
);
);
self::$baseDir is __DIR__. I thought at run time PHP would evaluate this and save it out as path/to/some/dir/freya- ....
The exact error is:
Parse error: syntax error, unexpected '$baseDir' (T_VARIABLE), expecting identifier (T_STRING) or class (T_CLASS) in /vagrant/local-dev/content/mu-plugins/Freya-MU/bundles/BundleLoader.php on line 51
Line 51, is: 'Freya\\Bundle\\PageBuilder' => self::$baseDir . '/freya-bundle-pagebuilder/Freya/Bundle/PageBuilder'
So ... What am I missing and whats the proper way to do this?
PHP Version: 5.5
PHP does not allow this. PHP properties may be initialized to constant values, but only with constant values that are available at compile time. From the manual:
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
Whatever value your static property $baseDir holds is simply not available until the class definition is actually executed (i.e. runtime).
You can get around this to a degree by using a class constant:
class AClass {
const MY_CONSTANT = 42;
protected $property = self::MY_CONSTANT;
}
Class constants are evaluated at compile time, which is what you need to do. Note however that you cannot do any other manipulations (e.g. initialize $property to be self::MY_CONSTANT * 3)
I would suggest leaving self::$baseDir completely out of your property, and either inject it in during construction or whenever your property is actually being used.
You can't use a variable when declaring a property in a class. Check out the invalid property declarations in the PHP manual.
<?php
class SimpleClass
{
// invalid property declarations:
public $var1 = 'hello ' . 'world';
public $var2 = <<<EOD
hello world
EOD;
public $var3 = 1+2;
public $var4 = self::myStaticMethod();
public $var5 = $myVar;
This is because PHP doesn't execute any code when parsing/compiling your class.
Just in addition to the other answers really: PHP 5.5 doesn't allow expressions, including concatenation, in default value definitions, but 5.6 does. (http://php.net/manual/en/migration56.new-features.php)
So, basically, either upgrade your PHP version or set the value of $bundles from a method. There is no problem with your array otherwise.
I'm trying to insert a static variable in an array like this :
static $datas = array(
'link' => config::$link
);
But i'm having this error
Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING
I discovered PHP doc say that :
Like any other PHP static variable, static properties may only be
initialized using a literal or constant; expressions are not allowed.
So while you may initialize a static property to an integer or array
(for instance), you may not initialize it to another variable, to a
function return value, or to an object.
But I'm sure there is a way to do that, any suggestion ?
No, there is no workaround. static variables and properties can only be initialized with constant values. That means literals or constants. Variables, static or not, cannot be used, period. You have to assign a variable value later using procedural code somewhere.
I saw this code in a PHP book (PHP architect, ZEND PHP 5 Certification guide page 141)
class foo{
public $bar;
protected $baz;
private $bas;
public var1="Test"; //String
public var2=1.23; //Numericvalue
public var3=array(1,2,3);
}
and it says
Properties are declared in PHP using one of the PPP operators, followed by their
name:
Note that, like a normal variable, a class property can be initialized while it is being
declared. However, the initialization is limited to assigning values (but not by
evaluating expressions). You can’t,for example,initialize a variable by calling a function—that’s something you can only do within one of the class’ methods (typically,
the constructor).
I can not understand how var1, var2, var3 are declared. Isn't it illegal?
The sample code is (almost) valid (it's just missing a few $ signs.)
class foo
{
// these will default to null
public $bar;
protected $baz;
private $bas;
// perfectly valid initializer to "string" value
public $var1 = "Test"; //String
// perfectly valid initializer to "float" value
public $var2 = 1.23; //Numericvalue
// perfectly valid initializer to "array" value
// (array() is a language construct/literal, not a function)
public $var3 = array(1,2,3);
}
So, the book your code comes from is definitely in error.
No, this is an error. Defining:
public var1="Test"; //String
Will give you:
Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE
For details, see http://codepad.org/meMrSmfA.
Variables in PHP are "represented by a dollar sign followed by the name of the variable". Although dollarless variables have been requested, I doubt whether they we ever see them enabled.
Point in short: your code is invalid.
In php variable are auto casting.whatever you want keep in a variable no need to declare it type .
But one mandatory thing is that when you going to declare a Variable in php you must have to use "$"
which one you missed .Book declaration is
public var1="Test"; //String
public var2=1.23; //Numericvalue
public var3=array(1,2,3);
its a wrong declaration
Right is
public $var1="Test"; //String
public $var2=1.23; //Numericvalue
public $var3=array(1,2,3);
that's other wise every thing are fine .
Thank you
static $PATH_TO_USER = $server . '/users';
I'm getting a syntax error. If I remove the static, it accepts it, though.
It's not a big deal to type the whole thing out, but I'm not sure why this isn't working in the first place
Static variable
Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error.
via the PHP Manual.
Static property
Like any other PHP static variable,
static properties may only be
initialized using a literal or
constant; expressions are not allowed.
via the PHP Manual.