As you can't have an array in a define or a class constant I thought I'd create an abstract class for configuration data for my project that needs to be more structures than simple values.
At first I thought I'd try something like the following, but this resulted in a syntax error on line 6:
<?php
abstract class Config
{
static private
$paths = array (
'classes' . _DS . 'cmsItems',
'classes' . _DS . 'dbdrivers',
'classes' . _DS . 'core'
);
static public function getPaths ()
{
return self::$paths;
}
}
?>
I then tried defining a static array inside the getter instead of a private property.
<?php
abstract class Config
{
static public function getPaths ()
{
static $paths = array (
'classes' . _DS . 'cmsItems',
'classes' . _DS . 'dbdrivers',
'classes' . _DS . 'core'
);
return $paths;
}
}
?>
This just resulted in a syntax error on line 7
But if I removed the static keyword...
<?php
abstract class Config
{
static public function getPaths ()
{
开发者_开发百科 $paths = array (
'classes' . _DS . 'cmsItems',
'classes' . _DS . 'dbdrivers',
'classes' . _DS . 'core'
);
return $paths;
}
}
?>
This seems to work fine (except now the array is created every time the function runs, which seems a bit wasteful to me).
Can anybody explain what's going on here?
(FYI, _DS is defined elsewhere and is simply an alias to DIRECTORY_SEPARATOR)
Quoting the page Static Keyword :
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed.
Yes, just after that, it is said :
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, still, expressions are forbidden.
When using this :
static private
$paths = array (
'classes' . _DS . 'cmsItems',
'classes' . _DS . 'dbdrivers',
'classes' . _DS . 'core'
);
You are having expressions in there -- I'm thinking about the strings concatenations : the content of your array is not constant, it is not known at compile time (one cannot know it just looking at this portion of code).
If you remove those expressions, and your code looks like this (for example ; I just replaced the concatenations with a _
in the strings) :
static private
$paths = array (
'classes_cmsItems',
'classes_dbdrivers',
'classes_core'
);
There will be no expression -- and, so, no error.
From : http://php.net/manual/en/language.oop5.static.php
"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."
Your line : 'classes' . _DS . 'cmsItems'
is an expression, and thus the error.
精彩评论