This question already has answers here:
How and why use curly braces: return $this->{$this->action}();
(2 answers)
Closed 6 years ago.
Feel free to re-title this Question because I do not know the proper name for doing this. More to the point, I have seen people using {'property'} when accessing a property inside an object so I set-up an example to try understand however, the property is accessible when I use it and when I don't?
class Example {
public $name;
}
$e = new Example();
$e->{'name'} = 'Kdot';
echo $e->name; // output: Kdot
I have tried changing the scopes and accessing it through a class method but it works both ways, again.
Can someone help me understand what the meaning of using the {} delimiters are? Because from my knowledge, if you stored the parameter inside another variable, this would also work:
$property = 'name';
echo $e->$property; // output: Kdot
They're mostly both just different ways to do the same thing, but with slightly different capabilities.
One difference is that if you want to concatenate inline and use that for a property name, you need the braces:
// example:
$property = 'foo';
echo $e->{$property . 'Suffix'}; // good, uses $e->fooSuffix
echo $e->$property . 'Suffix' // bad, uses $e->foo and adds "Suffix" literal
As well as that, directly access property names need to conform to certain rules. For example if you have a dash in your property name you need to use braces to access it.
Related
This question already has answers here:
Should an array be declared before using it? [closed]
(7 answers)
Closed 7 years ago.
In most languages, I have to initialize an associative array before I can use it:
data = {}
data["foo"] = "bar"
But in PHP I can just do
data["foo"] = "bar"
Are there any repercussions to doing this? Is this "the right way" to write PHP?
Is the same, but is not a good idea, the next is a copy-paste from php documentation.
If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.
Basically it's the same, and no you won't find any problem or repercussion.
But if you like you can do this:
$a = array();
You can read more in the PHP page
This question already has answers here:
Static methods in PHP: what for?
(2 answers)
Closed 8 years ago.
I'm trying to figure out what static vars are.
They can be access without instantiating the class but what other benefits do they have and when should they be used?
For example, my class has a private var which holds the name of the twitter feed i'm trying to get.
Should this be static? It never needs to change.
Generally things which aren't instance specific but needs to be stored in a variable should be static variables. Otherwise this manual tells the details: http://php.net/manual/en/language.variables.scope.php
Otherwise you can consider using constants also. For the example you mentioned (as others wrote) using constants seems to be the most sensible. (Either a class constant, or simple one.)
Static variables are for when you want a variable inside a function to keep it's value if the function is called again.
An example of a static variable could be the following.
function addOne(){
static $i = 0;
$i++;
return $i;
}
echo addOne();
echo addOne();
echo addOne();
Which would return
123
Without the static keyword, this would simply return
111
In your question, you mention you have data that won't need to be changed. As the comments in the question state, you should make this a Constant.
In short, static variables can be used for constants.
For example, a Math class can have static variables; PI etc.
Let's say you have something in a class that you need later.
Now, you need that thing but you don't actually need|want|should create a new instance of that class.
That's why you use a static method/property
This question already has answers here:
PHP curly brace syntax for member variable
(5 answers)
Closed 9 years ago.
http://www.php.net/manual/en/functions.variable-functions.php#24931
That function does something like $this->{$this->varname}(). I tried it out and confirmed that that's valid syntax but it leaves me wondering... where does php.net discuss the use of curly brackets in variable names like that?
Variable variables:
Class properties may also be accessed using variable property names. ...
Curly braces may also be used, to clearly delimit the property name.
See examples on that page, too.
Why shouldn't it work?
These are variable variables/function names.
$f = "time";
$f(); // returns the actual time
It's now the same, only in object context (http://php.net/manual/en/functions.variable-functions.php):
$object->$f; // calls the method with the name $f in $object
Now, to say that it is the method with the name $this->varname, you need to write $this->{$this->varname} as $this->$this->varname will be interpreted as ($this->$this)->varname which results in $this->{$this->__toString()}->varname what you don't want.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Parse error on explode('-','foo-bar')[0] (for instance)
In PHP there are functions that return an array, for example:
$a = parse_url("https://stackoverflow.com/q/9461027/87015");
echo $a["host"]; // stackoverflow.com
My question is how to combine the above two statements into a single statement. This (is something that works in JavaScript but) does not work:
echo parse_url("https://stackoverflow.com/q/9461027/87015")["host"];
Note: function array dereferencing is available since PHP 5.4; the above code works as-is.
You can do a little trick instead, write a simple function
function readArr($array, $index) {
return $array[$index];
}
Then use it like this
echo readArr(parse_url("http://stackoverflow.com/questions/9458303/how-can-i-change-the-color-white-from-a-uiimage-to-transparent"),"host");
Honestly, the best way of writing your above code is:
$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a["scheme"];
echo $a["host"];
Isn't that what I originally posted?
Yes. Depending on context you may want a better name than $a (perhaps $url), but that is the best way to write it. Adding a function is not an attractive option because when you revisit your code or when someone reads your code, they have to find the obscure function and figure out why on earth it exists. Leave it in the native language in this case.
Alternate code:
You can, however, combine the echo statements:
$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a['scheme'], $a['host'];
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP class instantiation. To use or not to use the parenthesis?
Omission of brackets and parameter-less object constructors
With or without the brackets, the new Class seems not bother. So, I doubt what's the usage of the brackets (). I searched php manual, didn't get it. Could anybody explain?
The purpose of the brackets is for you to enter any arguments that your constructor may accept.
class Example{
private $str;
public function __construct($str){
$this->str = $str;
}
public function output(){
echo $this->str;
}
}
$ex = new Example; // missing argument error
$ex = new Example('Something');
$ex->output(); // echos "Something"
If your class constructor does not accept any arguments, you may leave the brackets out. For good code sake, I always keep the brackets, whether or not the constructor accepts any argument.
Most coders coming from C# or Java background would keep the parenthesis as it is more familar to them.