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.
Related
I've been searching for quite a while and cannot find what this method is actually called.
In PHP example:
$var->{'property_name'}
Depending on what you are accessing it will be called...
A variable variable
A variable property
A variable function
It is worth noting that the curly-braces are only needed when you need to disambiguate an expression (bear in mind the string you use may itself be stored in a variable!)
And so on. This is documented in the PHP manual for variable variables.
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.
References:
If I pass a variable to a function (e.g. $var), is that supposed to be a copy of a reference to the actual variable (such that setting it null doesn't affect other copies)?
Or is it receiving a reference to what is a new copy of the actual variable (such that setting it to null destroys its copy only)?
If the latter, does this copy objects and arrays in memory? That seems like a good way to waste memory and CPU time, if so.
I think can understand passing by reference (e.g. &$var) correctly by knowing how this works, first.
Scope:
What's the deal with local scope? Am I right in observing that I can declare an array in one function and then use that array in other functions called within that function WITHOUT passing it to them as a parameter?
Similarly, does declaring in array in a function called within a function allow it to be available in the caller?
If not, does scoping work by a call stack or whatever like every bloody thing I've come to understand about programming tells me it should?
PHP is so much fun. :(
If I pass a variable to a function (e.g. $var), is that supposed to be a copy of a reference to the actual variable (such that setting it null doesn't affect other copies)?
Depends on the function. And also how you call it. Look at this example:
http://www.ideone.com/LueFc
Or is it receiving a reference to what is a new copy of the actual variable (such that setting it to null destroys its copy only)?
Again depends on the function
If the latter, does this copy objects and arrays in memory? That seems like a good way to waste memory and CPU time, if so.
Its going to save memory to use a reference, certainly. In php>4 it always uses reference for objects unless you specify otherwise.
What's the deal with local scope? Am I right in observing that I can declare an array in one function and then use that array in other functions called within that function WITHOUT passing it to them as a parameter?
No you can't.
Similarly, does declaring in array in a function called within a function allow it to be available in the caller?
No, it doesn't.
If not, does scoping work by a call stack or whatever like every bloody thing I've come to understand about programming tells me it should?
If you want to use a variable from outside the function, before using it, you'd write global $outsidevar
Concerning your first set of questions:
foo($a);
function foo($b) { echo $b; }
In this case, $a will not be copied to a new variable $b, only because it is passed by value.
This is because PHP uses the copy-on-write concept. PHP will not copy the contents of a variable, unless they are changed. Instead PHP will increment the refcount property of the existing "zval" of $a.
Well, the whole thing is not that trivial, but to answer your question: No, it does not copy the variable, unless you write to it in the function and no, you won't save CPU and Memory by using a reference. In most cases the reference won't change performance at all, but in the worst case it will actually degrade it (because if a not is_ref variant of the variable already exists and a reference is created the value of the variable must be copied to get a zval with is_ref and one without). Optimizing code by using references is no good.
if argument to a function is defined as so "function my_function($variable) {}" then you are getting a copy of the variable and any alterations made to the variable inside your function will not be available to the function caller. you can pass a variable by reference by prepending an ampersand to the argument when defining your function and thus any alterations made to the variable will persist to the function caller, ie "function my_function(&$variable) {}"
function myfunction($var) {
$var = 'World';
}
$var = 'Hello';
myfunction($var);
echo $var; // 'Hello';
Passing a variable by reference
function myfunction(&$var) {
$var = 'World';
}
$var = 'Hello';
myfunction($var);
echo $var; // 'World'
I just stumbled upon an interesting syntax in a PHP script:
echo $foo->{'bar'};
$foo in this case is an object returned from PHP's json_decode() function, but it works well when accessing public members of any object.
I've tried to find out why this syntax was used instead of the more common:
echo $foo->bar;
Does accessing a class member with the syntax from the first example offer anything special, compared to the second example?
The curly bracket syntax is useful when you want to reference a function name as a string:
print $foo->{'aMemberFunc'}();
When you want access members which name is provided by another function (or a variable).
Here getVarName() returns a string which can be used to reference a member inside the $foo object.
print $foo->{getVarName()};
Without the curly brackets it would be $foo->getVarName() and it would try and run that method... with the curly brackets it takes a completely different meaning.
echo $foo->{'bar'}; and echo $foo->bar; are identical as far as I can tell.
first syntax allows you to access properties with '-', often used in JSON.
The benefit is that you can have variables names that don't adhere to the rules for naming member variables.
This might seem like a bad idea and usually it is but there are uses for it. An example would be if you were writing an application that allowed its users to add arbitrary fields with human readable names but still be accessible for plugins etc.
How can I dynamically pass "items" to class function?
For example here it is a piece of some class and its function where I declare an element of object (items) as $b:
//..........
public function __add2SomeObj($b) {
$namespc = $this -> __someObj(); // __someObj() returns object
$namespc -> cats = $b;
}
//...................
Can I pass any other name instead cats dynamically so it won't be declared as a string?
i.e. something like:
//..........
public function __add2SomeObj($a,$b) {
$namespc = $this -> __someObj(); // __someObj() returns object
$namespc -> $a = $b;
}
//...................
} //end of class started above
$t=new aboveClass()
$t->__add2SomeObj("cats", array(1=>"PussyCat",2=>"Scratchy"));
$t->__add2SomeObj("dogs", array(1=>"Waffy",2=>"Sharik")); // once again but dogs...
Should I define a constant or what to make this or should i declare this protected varibale as object like (object) $vaaar?
Sorry I'm a little bit infamiliar with PHP OOP...
Yes you can do this. Read about variable variables:
Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.
However you must be carful when dealing with arrays:
$namespc->$a[0]
will get the first element from the array that gets returned by $namespc->$a.
Whereas
$namespc->{$a[0]}
will first resolve $a[0], i.e. get the first value of the array $a, and use this as property name.
What you're asking is whether you can decide at runtime which property to change inside __add2SomeObj as you in the second listing. You can, and you did is correct.
However, properties must be strings __add2SomeObj, so you should ensure that the $a parameter is a string (it will be automatically converted to a string, but this may give unexpected results if $a is an object or an array).
Second, you're allowing the caller too change an arbitrary property. This may or may not violate the encapsulation of your class depending on the class __someObj returns and on the class of __add2SomeObj. It will also create a dynamic property on the object $namespce (i.e., one that does not exist in all the objects of that class), which you may not want.
Finally, and has a consequence of the point before, __add2SomeObj may generate a fatal error. So I'd say you'd better validate the $a paramater against a set of permitted property names.
You syntax is correct:
$obj->cats = $b;
and
$a = 'cats';
$obj->$a = $b;
will do the same thing.
As for whether or not to make "cats" a constant, that's up to you. I would suggest putting the error reporting up:
error_reporting(E_ALL | E_STRICT);
That way if you accidentally put in "cast" and that's not a valid member you'll get an error thrown.
Lastly, PHP is a dynamic language. I get the feeling your background might be with more static languages. This is just something you need to get comfortable with and you need to find a balance between readability and verbosity. But whatever you do, don't try and recreate non-PHP idioms in PHP, which is a common mistake for people coming from one language to another.