Variable within an array PHP - 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

Related

Why PHP doesn't allow to declare static closure property? [duplicate]

...
public $aSettings = array(
'BindHost' => "127.0.0.1",
'Port' => 9123,
'MaxFileSize' => (5 * (1024 * 1024)), // unexpected "(" here
'UploadedURL' => "http://localhost",
'UploadPath' => dirname(__FILE__) . "/upload",
'UploadMap' => dirname(__FILE__) . "/uploads.object",
'RegisterMode' => false
);
...
This is my code, straight from a class. The problem I have is the "unexpected ( on line 22", line 22 being MaxFileSize.
I can't see a problem with it, is this a Zend Engine limitation? Or am I blind.
You cannot use non-constant values while initializing class properties in PHP versions earlier than 5.6.
These are initialized at compile time, at which PHP will do no calculations or execute any code. (5 * (1024 * 1024)) is an expression that requires evaluation, which you cannot do there. Either replace that with the constant value 5242880 or do the calculation in __construct.
PHP 5.6, introduced in 2014, allows "constant scalar expressions" wherein a scalar constant or class property can be initialized by an evaluated expression in the class definition rather than the constructor.
I suspect this is not the whole code and this is a definition of a static variable inside a class, where you're quite limited in expressions and can't calculate a lot.
If I'm right, you may want to do something like that instead:
class thingamajig {
public static $aSettings;
};
thingamajig::$aSettings = array ( ... );
P.S. Sorry, I've just read your prose where you confirm it's a part of a class static variable. So you can't just ignore out-of-place keyword.
I assume what you're showing is actually a class property (because of the public keyword). Initialization of class properties in PHP must be constant.
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.
http://www.php.net/manual/en/language.oop5.properties.php
When you define variable in class, you cannot assign expression to it. (5 * (1024 * 1024)) is an expression. 6164480 is not.
This limitation no longer exists as of PHP 5.6
The new feature that enables the previously-disallowed syntax is called constant scalar expressions:
It is now possible to provide a scalar expression involving numeric
and string literals and/or constants in contexts where PHP previously
expected a static value, such as constant and property declarations
and default function arguments.
class C {
const THREE = TWO + 1;
const ONE_THIRD = ONE / self::THREE;
const SENTENCE = 'The value of THREE is '.self::THREE;
public function f($a = ONE + self::THREE) {
return $a;
}
}
echo (new C)->f()."\n"; echo C::SENTENCE; ?>
The above example will output:
4 The value of THREE is 3
Public is a declaration only used in objects. This is not an object, remove public and it's fine.

PHP - Anonymous Classes inside Anonymous Classes [duplicate]

...
public $aSettings = array(
'BindHost' => "127.0.0.1",
'Port' => 9123,
'MaxFileSize' => (5 * (1024 * 1024)), // unexpected "(" here
'UploadedURL' => "http://localhost",
'UploadPath' => dirname(__FILE__) . "/upload",
'UploadMap' => dirname(__FILE__) . "/uploads.object",
'RegisterMode' => false
);
...
This is my code, straight from a class. The problem I have is the "unexpected ( on line 22", line 22 being MaxFileSize.
I can't see a problem with it, is this a Zend Engine limitation? Or am I blind.
You cannot use non-constant values while initializing class properties in PHP versions earlier than 5.6.
These are initialized at compile time, at which PHP will do no calculations or execute any code. (5 * (1024 * 1024)) is an expression that requires evaluation, which you cannot do there. Either replace that with the constant value 5242880 or do the calculation in __construct.
PHP 5.6, introduced in 2014, allows "constant scalar expressions" wherein a scalar constant or class property can be initialized by an evaluated expression in the class definition rather than the constructor.
I suspect this is not the whole code and this is a definition of a static variable inside a class, where you're quite limited in expressions and can't calculate a lot.
If I'm right, you may want to do something like that instead:
class thingamajig {
public static $aSettings;
};
thingamajig::$aSettings = array ( ... );
P.S. Sorry, I've just read your prose where you confirm it's a part of a class static variable. So you can't just ignore out-of-place keyword.
I assume what you're showing is actually a class property (because of the public keyword). Initialization of class properties in PHP must be constant.
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.
http://www.php.net/manual/en/language.oop5.properties.php
When you define variable in class, you cannot assign expression to it. (5 * (1024 * 1024)) is an expression. 6164480 is not.
This limitation no longer exists as of PHP 5.6
The new feature that enables the previously-disallowed syntax is called constant scalar expressions:
It is now possible to provide a scalar expression involving numeric
and string literals and/or constants in contexts where PHP previously
expected a static value, such as constant and property declarations
and default function arguments.
class C {
const THREE = TWO + 1;
const ONE_THIRD = ONE / self::THREE;
const SENTENCE = 'The value of THREE is '.self::THREE;
public function f($a = ONE + self::THREE) {
return $a;
}
}
echo (new C)->f()."\n"; echo C::SENTENCE; ?>
The above example will output:
4 The value of THREE is 3
Public is a declaration only used in objects. This is not an object, remove public and it's fine.

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.

Static variable in static array

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.

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.

Categories