Static variable in static array - php

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.

Related

Missing the fundamentals of arrays in PHP

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.

Variable within an array PHP

I want the variable to be parsed within the array so when I echo $head['meta_title'] , lol is displayed. I have tried wrapping it in double quotes but that doesn't seem to work either, is there any way round this?? Thanks!
I am getting either unexpected T_VARIABLE and when I use double quotes I get unexpected ""
$meta_title = "lol";
public $head = array
(
"title" => "blah",
"meta_title" => $meta_title,
"meta_content" => $meta_content
);
You cannot use an expression to initialize a class property. The values of the two variables are not known until runtime, and therefore can't be used in the declaration. Instead, define them in the constructor.
public $head = array
(
// The title as a string literal is ok...
"title" => "blah",
"meta_title" => NULL,
"meta_content" => NULL
);
// Pass them to the constructor as parameters
public function __construct($meta_title, $meta_content)
{
// Initialize them in the constructor.
$this->head['meta_title'] = $meta_title;
$this->head['meta_content'] = $meta_content;
}
From the docs
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. 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.
If this is within an object you cannot assign a variable this way. You have to set it using the __construct-method.
The public needs to be removed before $head. I've created an example in PHP Sandbox.
http://sandbox.onlinephpfunctions.com/code/d17bc90e1291f6a3b23537984df755e40446add6

PHP error, concatenation in array() in member initialiser

I'm getting an error with the following code:
public $arr = array('email' => 'admin#' . str_replace('http://', '', SERVER_ROOT));
Parse error: syntax error, unexpected '.', expecting ')'
Am I being really stupid? Surely I can concatenate strings here?
This is a variable declared in a class.
You cannot initialize class attributes with an expression. You have to do that in the constructor or use a fixed value, like a regular string.
This is an error, you can't initialize a property like this
Properties
Class member variables are called "properties". You may also see them
referred to using other terms such as "attributes" or "fields", but
for the purposes of this reference we will use "properties". They are
defined by using one of the keywords public, protected, or private,
followed by a normal variable declaration. This declaration may
include an initialization, but this initialization must be a constantvalue--that is, it must be able to be evaluated at compile time andmust not depend on run-time information in order to be evaluated.

Can I declare a variable without $ in PHP

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

Can't use a variable inside static variable definition?

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.

Categories