I have a very simple issue where I am trying to set a private static property value made up of a constant appended with some text like this:
private static $cssDirectory = APP_ROOT.'css/';
I am getting a syntax error. I can fix this by making the private variable not static and assign a value with a constructor for example but since I want it static I am curious what can I do about it. I can also make a constant for the whole value and use that but again I am curious why I can't do it like I tried. Maybe I am doing something wrong also. Thanks.
From the PHP docs
Class member variables are called "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.
Concatenation is a run-time operation.
You don't need to instantiate and set the property value in the constructor.... you can write a static setter method instead
Note also that PHP 5.6 does allow this type of initialization of class properties
EDIT
Example of a static setter method:
private static $cssDirectory;
public static setCssDirectory() {
self::$cssDirectory = APP_ROOT.'css/';
}
And then you just call
myClassName::setCssDirectory();
before anything else
Related
trait Foo {
private $url = config('api.url');
}
I have a url data set inside of config, however I need to put this value into trait's property. But it's not working. anyone know how to solve this problem?
what I did now is put construct inside of trait
public function __construct(){
$this->url = config('api.url');
}
it's not about traits, it's about php OOP nature itself:
here is 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.
from the docs example:
// invalid property declarations:
public $var4 = self::myStaticMethod();
public $var5 = $myVar;
Up until today, I thought I had a fairly good grasp of how the static modifier worked. I know that (in laymans terms) a static variable in a function does not 'reset' across calls to that function, and I know that static variables and functions on a class are accessible by calling upon them through the class itself (not an instantiation of the class).
My problem is this: today I found that if I declare a static variable inside of a non-static function on a class, all instantiations of that class share that static variable in separate calls to the member function.
For example:
class A {
public function GetValue() {
static $value = 0;
$value++;
return $value;
}
}
$instance_1 = new A();
$instance_2 = new A();
echo $instance_1->GetValue();
echo $instance_1->GetValue();
echo $instance_2->GetValue();
echo $instance_2->GetValue();
echo $instance_1->GetValue();
echo $instance_1->GetValue();
Notice that the GetValue function is neither declared as static or used in a static way (as in, called on the class itself).
Now, I always assumed that this would output: 121234
Instead, I find that it will output: 123456
Like I say, I would understand this if the static variable $value was inside of a static function. However, with it being inside a non-static function I just assumed that it would only be 'tied' to the function 'within' each individual instantiation.
I guess my question is twofold, then... 1) is this a bug or expected behaviour? 2) do other languages treat these 'static inside non-static' variables the same way, or is this unique to PHP?
This is expected.
This is also the case in C++ (and probably others as well).
You should think of non-static class member functions as if they were just like ordinary functions, but with an implicit $this argument that is automatically provided by the interpreter. (That's exactly how they're implemented in most languages.)
I've copied the following information from this article by Josh Duck: http://joshduck.com/blog/2010/03/19/exploring-phps-static-scoping/
Static variables have been available since PHP 4 and allow you to define a persistent variable that is only accessible from the current function. This allows you to encapsulate state into a function or method and can eliminate the need for classes where a single function will suffice.
When a static variable is defined inside a class method they will always refer to the class on which the method was called. In doing this they act almost like properties referenced through static, though there are subtle differences.
Static variables can’t preserve the calling class scope. This can be potentially problematic if you have an inherited method containing a static variable that is called from both inside and outside its class.
As far as I know, all languages with static variables treat them this way. Think of static variables as global variables that can only be accessed from a certain scope.
why does this not work ?
class Test{
private $vars = array('ALL' => 0,
'ONE' => 1);
private $var = $vars['ALL']; // this does not work
function __construct(){
$this->var = $vars['ALL']; // this does work
}
}
code example here: http://codepad.org/QSjHMDij
why is the array not accessible in the statement
private $var = $vars['ALL']; // this does not work
Probably because you can't access $this during the initialization of the class prior to the constructor getting called (which is implied when you tried to do it in the definition for $var.) Some languages (like C#) will let you do it, but I think PHP is one that will not.
Neither "works" in the way you intend. You are not allowed to use variables when declaring instance members (hence the unexpected T_VARIABLE error). In the constructor you are referencing a local variable named $vars which does not exist, meaning you're setting $this->var to NULL.
Access the instance member by doing $this->vars. You can only do this in the constructor.
When declaring members (variables), you can't assign array key values of other members, it causes a parse error.
For example, you're thinking (wrong) that $vars['ALL'] is referring to your private $var - which it is not - it also causes a parse error. There's no way for PHP to know that when you say:
private $var = $vars['ALL'];
that you're actually saying "I want value of $this->vars['ALL'] to be assigned to $this->var", at least not the way you wrote it. That's why you do that from within a function, where you can easily manipulate members, such as you did from the constructor.
You should declare members, their visibility and set some default values (like you did for $var), but you shouldn't point them to other members' values, it's simply - wrong and luckily - it doesn't work :)
You're trying to assign a value to a variable which is designed to be part of an object, rather than the class. What you want is static variables.
Here is my class
class Databases {
public $liveresellerdb = new Database('1host1','user','pswd','db');
}
the error i am getting is
Parse error: syntax error, unexpected T_NEW in /home/abhijitnair/sandbox/newreseller/Databases.php on line 33
why this error is coming?
Properties may not be preset with runtime information.
Quoting PHP Manual:
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.
<?php
class Databases {
public static $liveresellerdb;
}
Databases::$liveresellerdb = new Database('1host1','user','pswd','db');
?>
This is how you initialise a static member...
Because you forgot to write the static keyword to actually make the property static.
In addition, you can't initialise static properties with expressions like this. Here's a workaround.
you cannot assign object during the class preperation stages, only the class instantation:
class Databases
{
public $liveresellerdb;
public function __construct()
{
$this->liveresellerdb = new Database('1host1','user','pswd','db');
}
}
anything within the constructor can be generic PHP code, outside the function and instead the class body has specific laws.
if you require the database's to be static then you have to set / access them differently.
class Databases
{
public static $liveresellerdb;
}
Databases::liversellerdb = new Database('1host1','user','pswd','db');
starting use oop
why:
class user
{
private $pdo;
function __construct()
{
$this->pdo = singleton::get_instance()->PDO_connection();
}
...
}
this works fine. but this:
class user
{
private $pdo = singleton::get_instance()->PDO_connection();
...
}
this does not working. Error parse error, expecting ','' or ';'' in ...
what is wrong with second variant?
See the last sentence of the first paragraph of Properties in the PHP OOP documentation:
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.
In other words, the database handler returned by this statement is not a constant value and therefore will not be available at compile time:
singleton::get_instance()->PDO_connection();
Class properties cannot be assigned at declaration using functions. Scalar values, constants (though not constants of the current class), and arrays only.